Inorder Successor in BST Problem
Description
LeetCode Problem 285.
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, 10^4]. -10^5 <= Node.val <= 10^5- All Nodes will have unique values.
Solution
Approach: Binary Search Down the Tree
The in-order successor of p is the node with the smallest value greater than p.val. In a BST we can search for it from the root, the same way we search for a value, without a full traversal.
At each node:
- If
node.val > p.val, this node could be the successor. Remember it, then go left to look for a smaller value that is still greater thanp.val. - Otherwise (
node.val <= p.val), this node and its whole left subtree are too small, so go right.
When we fall off the tree, the last node we remembered is the successor. If we never remembered one, every value is at most p.val and the answer is null (Example 2, where p is the largest value).
This handles both classic cases without special code: when p has a right subtree, the search walks into it and finds its leftmost node. When it does not, the remembered node is the closest ancestor whose left subtree contains p.
Complexity: O(h) time, where h is the height of the tree. O(1) extra space.
class Solution:
def inorderSuccessor(self, root: TreeNode, p: TreeNode) -> Optional[TreeNode]:
successor = None
node = root
while node:
if node.val > p.val:
successor = node # a candidate; a smaller one can only be in its left subtree
node = node.left
else:
node = node.right # too small: the successor is to the right
return successor