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. Think of it as finding the "next" node that would appear after p in a sorted traversal of the tree.
Key Insight: In a BST, the inorder traversal visits nodes in sorted order. The inorder successor is simply the next node in this sorted sequence.
Example: If we have nodes with values [1, 3, 6, 7, 8, 10, 13] in inorder traversal, then the successor of node 6 is node 7, and the successor of node 13 is null (no larger value exists).
Input & Output
Visualization
Time & Space Complexity
In worst case, traverse from root to leaf, where h is height of tree. For balanced BST, h = log(n)
Only uses a few pointer variables, no additional data structures needed
Constraints
- The number of nodes in the tree is in the range [1, 104]
- -105 โค Node.val โค 105
- All Nodes will have unique values
- p will exist in the BST