Inorder Successor in BST II - Problem
Given a node in a binary search tree, return the in-order successor of that node in the BST. If that node has no in-order successor, return null.
The successor of a node is the node with the smallest key greater than node.val.
You will have direct access to the node but not to the root of the tree. Each node will have a reference to its parent node.
The definition for Node is:
class Node {
public int val;
public Node left;
public Node right;
public Node parent;
} Input & Output
Example 1 — Node with Right Subtree
$
Input:
node = Node(3) in BST [2,3,4,5,6,7,8]
›
Output:
Node(5)
💡 Note:
Node 3 has a right subtree starting with 5. The leftmost node in this right subtree is 5, so the successor is 5.
Example 2 — Node without Right Subtree
$
Input:
node = Node(4) in BST [2,3,4,5,6,7,8]
›
Output:
Node(5)
💡 Note:
Node 4 has no right subtree. We go up to parent 3, then to parent 5. Since 4→3→5 and we came from the left at 5, the successor is 5.
Example 3 — Rightmost Node
$
Input:
node = Node(8) in BST [2,3,4,5,6,7,8]
›
Output:
null
💡 Note:
Node 8 is the rightmost node in the BST, so it has no inorder successor. Return null.
Constraints
- The number of nodes in the tree is in the range [1, 104]
- -105 ≤ Node.val ≤ 105
- All Node.val are unique
Visualization
Tap to expand
Understanding the Visualization
1
Input
Given a node in BST with parent pointers
2
Process
Use BST properties to find successor efficiently
3
Output
Return the inorder successor or null
Key Takeaway
🎯 Key Insight: Use BST structure and parent pointers to find successor in O(h) time without full traversal
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code