Given the root of a Binary Search Tree (BST) and a node p in the tree, return the in-order successor of p.
- The in-order successor of a node is the node with the smallest value strictly greater than
p.val - If no such node exists, return
null
Because the tree is a BST, we do not need to perform a full inorder traversal.
The problem reduces to finding the minimum value greater than
p.val
This is equivalent to performing a lower bound search in a BST.
We traverse the tree starting from root and maintain a candidate successor.
- If
curr.val > p.valcurris a valid successor candidate- Save it
- Move to the left subtree to find a smaller valid successor
- Else (
curr.val <= p.val)- The successor must be in the right subtree
- Move right
- Initialize
ans = nullptr - Set
curr = root - While
curris not null:- If
curr.val > p.val:- Update
ans = curr - Move to
curr.left
- Update
- Else:
- Move to
curr.right
- Move to
- If
- Return
ans
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
public:
TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
TreeNode* res = nullptr;
TreeNode* curr = root;
while (curr) {
if (curr->val > p->val) {
res = curr; // candidate successor
curr = curr->left; // try to find a smaller one
} else {
curr = curr->right; // must go right to find larger values
}
}
return res;
}
};- Any node with value
<= p.valcannot be the inorder successor - Every node with value
> p.valis a valid candidate - Moving left ensures we find the smallest such candidate
- This approach avoids unnecessary traversal and extra memory usage
- Time Complexity:
O(h)his the height of the tree- Balanced BST:
O(log n) - Worst case (skewed tree):
O(n)
- Space Complexity:
O(1)
“Since this is a BST, we can find the inorder successor using a lower-bound style search in
O(h)time andO(1)space, without doing a full inorder traversal.”

