Inorder Successor in BST - Problem
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.
Input & Output
Example 1 — Node with Right Subtree
$
Input:
root = [2,1,3], p = 1
›
Output:
2
💡 Note:
Node 1 has no right child, so we look for the ancestor where 1 is in the left subtree. Starting from root 2, since 1 < 2, node 2 is the successor of 1.
Example 2 — Node without Right Subtree
$
Input:
root = [5,3,6,2,4,null,null,1], p = 6
›
Output:
null
💡 Note:
Node 6 has no right child and is the largest node in the BST, so it has no inorder successor. Return null.
Example 3 — Leftmost in Right Subtree
$
Input:
root = [5,3,6,2,4], p = 3
›
Output:
4
💡 Note:
Node 3 has a right child. The successor is the leftmost node in the right subtree of 3, which is node 4.
Constraints
- The number of nodes in the tree is in the range [1, 104]
- -105 ≤ Node.val ≤ 105
- All Node.val are unique
- p is a TreeNode in the tree
Visualization
Tap to expand
Understanding the Visualization
1
Input
BST and target node p
2
Process
Use BST properties to find successor
3
Output
Next node in inorder sequence
Key Takeaway
🎯 Key Insight: BST structure allows us to find successors in O(h) time by following specific paths rather than visiting all nodes
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code