Inorder Successor in BST
Candidate tracking during a single root-to-target search
The successor is either in p's right subtree (its minimum) or is the lowest ancestor of p reached by turning left. A single search from the root captures both cases without branching on them: every time p.val is smaller than the current node, that node is a candidate successor and the search continues left for something even closer; otherwise it moves right. Whatever candidate survives when the search runs off the tree is the answer.
Details
Animated on: root = [5,3,6,2,4,null,null,1], p = 3 — return the inorder successor of node p (the smallest value greater than p.val). Expected: 4.
Problem:Inorder Successor in BSTMedium
Candidate tracking during a single root-to-target search
step 1 / 15
Find the inorder successor of p = 3 (marked "p"): the node holding the smallest value greater than p.val. There are no parent pointers, so search down from the root instead of scanning the whole tree.
1FUNCTION inorderSuccessor(root, p):2 successor <- null3 curr <- root4 WHILE curr != null:5 IF p.val < curr.val:6 successor <- curr7 curr <- curr.left8 ELSE:9 curr <- curr.right10 RETURN successor11END FUNCTION
← / → step · space play · Home restart
Every step in words
Show all 15 steps
- Find the inorder successor of p = 3 (marked "p"): the node holding the smallest value greater than p.val. There are no parent pointers, so search down from the root instead of scanning the whole tree.
- Start: successor = null, curr = root (5).
- curr (5) is not null, so the loop continues. Compare p.val (3) to curr.val (5).
- 3 < 5, so curr (5) is bigger than p — it's a valid candidate successor.
- successor <- 5. It is the smallest node seen so far that is still bigger than p, so it's the current best answer.
- Searching further left might find something even smaller than 5 but still greater than p, so curr <- 3.
- curr (3) is not null, so the loop continues. Compare p.val (3) to curr.val (3).
- 3 >= 3, so curr (3) is p itself or smaller — it can never be the successor. Move right without touching successor.
- curr <- 4.
- curr (4) is not null, so the loop continues. Compare p.val (3) to curr.val (4).
- 3 < 4, so curr (4) is bigger than p — it's a valid candidate successor.
- successor <- 4. It is the smallest node seen so far that is still bigger than p, so it's the current best answer.
- curr.left is null, so curr becomes null and the loop ends.
- curr is now null, so the loop exits.
- RETURN successor. The inorder successor of 3 is 4. Only h nodes on the root-to-target path were ever visited, so this runs in O(h), not O(n).
Now solve it yourself
Watching is the first half. The second is writing it without the animation.