285. Inorder Successor in BST π
DifficultyMedium
Description
Given the root of a binary search tree and a node p in it, return the in-order successor of that node in the BST. If the given node has no in-order successor in the tree, return null.
The successor of a node p is the node with the smallest key greater than p.val.
Example 1:
Input: root = [2,1,3], p = 1 Output: 2 Explanation: 1's in-order successor node is 2. Note that both p and the return value is of TreeNode type.
Example 2:
Input: root = [5,3,6,2,4,null,null,1], p = 6 Output: null Explanation: There is no in-order successor of the current node, so the answer is null.
Constraints:
- The number of nodes in the tree is in the range
[1, 104]. -105 <= Node.val <= 105- All Nodes will have unique values.
Solutions
Solution 1: Binary Search
Thinking
The inorder successor is the smallest key greater than \(p\). On a BST we walk as in binary search: if the current key is larger it is a candidate and we go left; otherwise we go right.
The last candidate on that path is the successor, in time proportional to the height.
The in-order traversal of a binary search tree is an ascending sequence, so we can use the binary search method.
The in-order successor node of a binary search tree node \(p\) satisfies:
- The value of the in-order successor node is greater than the value of node \(p\).
- The in-order successor is the node with the smallest value among all nodes greater than \(p\).
Therefore, for the current node \(\textit{root}\), if \(\textit{root}.\textit{val} > p.\textit{val}\), then \(\textit{root}\) could be the in-order successor of \(p\). We record \(\textit{root}\) as \(\textit{ans}\) and then search the left subtree, i.e., \(\textit{root} = \textit{root}.\textit{left}\). If \(\textit{root}.\textit{val} \leq p.\textit{val}\), then \(\textit{root}\) cannot be the in-order successor of \(p\), and we search the right subtree, i.e., \(\textit{root} = \textit{root}.\textit{right}\).
The time complexity is \(O(h)\), and the space complexity is \(O(1)\), where \(h\) is the height of the binary search tree.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | |

