cur's path root first · ringed = p and q · faded = subtrees ruled out
Sorted order the BST's in-order values · faded = ruled out · cur splits p and q when it lies between them
cur
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { TreeNode cur = root; while (cur != null) { if (p.val > cur.val && q.val > cur.val) { cur = cur.right; } else if (p.val < cur.val && q.val < cur.val) { cur = cur.left; } else { return cur; } } return null;}
- p, q
- —
- cur
- —
- compare
- —
- steps down
- 0
Why it works
- Brute force ignores the ordering: record the root-to-p and root-to-q paths with a full search, then take the last node they share. O(n) time and O(n) space.
- The BST order tells you where p and q live. If both are bigger than
cur, both sit in its right subtree, so every common ancestor belowcuris on the right; same for the left. The first node where they fall on different sides (or that equals one of them) is the split point, and no deeper node can contain both. - One step per level: the walk only goes down, so it costs O(h), which is O(log n) for a balanced tree and O(n) for a chain. Nothing is stored but
cur: O(1) space. - Pitfall: forgetting that a node is its own ancestor. When
curequals p (or q), the other one is below it, socuris the answer; theelsebranch covers that because neither strict comparison holds. - Related: for a plain binary tree (problem 236) there is no ordering, so you need a post-order search that reports which of p and q each subtree contains.