Lowest Common Ancestor of BST
Lowest Common Ancestor of BST is LeetCode 235 (Medium). You get the root of a binary search tree and two of its nodes, p and q. Return their lowest common ancestor: the deepest node that has both p and q in its subtree.
- A node counts as its own descendant, so if
psits aboveq, the answer isp. - All values are unique,
p != q, and both nodes are in the tree. - The tree can hold up to 100,000 nodes and need not be balanced.
- The number of nodes in the tree is in the range [2, 10⁵].
- -10⁹ <= Node.val <= 10⁹
- All Node.val are unique.
- p != q
- p and q will exist in the BST.
Intuition
In a BST, every value in a node's left subtree is smaller than the node and every value in its right subtree is larger. So one comparison tells you where both targets live.
- Both smaller: both are in the left subtree, so the answer is down there.
- Both larger: both are in the right subtree.
- Otherwise: this node lies between them, or equals one of them. It is the split point, and it is the answer.
Why the split point? Below it, the left subtree holds only one target and the right subtree only the other, so no deeper node contains both.
When a tree question involves a BST, ask whether the ordering tells you which side to go without looking. Here it does, so a single walk down replaces a search of the whole tree.
Approach
Before reading on, stand at the root and decide what comparing it with p and q tells you. Then decide when to stop walking. Aim for O(h) time and O(1) space.
Two ways to solve it
Move one pointer down while both targets are on the same side.
- No stack: constant extra memory.
- Same logic: three cases per node.
The usual interview answer.
Call the function on the left or right child while both targets are on that side.
- Short: reads like the definition.
- Watch out: one stack frame per level.
Fine on balanced trees.
Both follow the same single path and run in O(h). The loop wins because it needs no call stack. The steps, code and live demo follow the loop, and the recursive code comes after the demo.
Start at the root
Set node = root. The root is an ancestor of every node, so the answer is somewhere on the path below it.
Move left when both targets are smaller
If p.val and q.val are both less than node.val, both nodes are in the left subtree, and so is a lower common ancestor. Move to node.left.
Move right when both are larger
If both values are greater than node.val, both targets are in the right subtree. Move to node.right.
Stop at the split
Otherwise return node: one target is on each side, or node is itself p or q. Because both targets are in the tree, the loop always reaches this point before running off the bottom.
Code in Python, C++ and Java
Recursion
The same three cases, with the move written as a call on the child instead of a pointer update. Each call returns the answer from below unchanged, so the stack holds one frame per level walked.
Common pitfalls
Using <= in the move tests
if p.val <= node.val and q.val <= node.val:
node = node.left
elif p.val >= node.val and q.val >= node.val:
node = node.rightif p.val < node.val and q.val < node.val:
node = node.left
elif p.val > node.val and q.val > node.val:
node = node.rightWith <=, a node equal to one target still moves on, walking past the answer. In the tree [6,2,8,0,4,7,9,null,null,3,5] with p = 2, q = 4, the loose test leaves 2, reaches 4, then steps on to 3 and returns 3. The answer is 2.
Recursing on a tree shaped like a chain
return self.lowestCommonAncestor(root.left, p, q)
node = node.left
Nothing keeps the tree balanced, so 100,000 sorted inserts make a chain 100,000 levels deep. With p and q at the bottom, Python's default recursion limit of 1,000 raises RecursionError; the loop uses no stack and finishes.
Edge cases
p = 2, q = 4At node 2, p.val equals the node, so neither the both-smaller nor the both-larger test holds, and 2 is returned without going deeper.
Complexity
Lowest Common Ancestor of BST FAQ
How does this differ from the binary tree version (236)?
Without the BST order, a node can't tell which side holds a target, so problem 236 has to search both subtrees, O(n). That method still works on a BST, but it ignores the free information the values give and visits nodes the walk here never touches.
Does this need p and q to be in the tree?
Yes. The walk never checks that a target exists; it only compares values. If q were missing, it would still return some node, or fall off the bottom and return nothing. When the targets might be absent, search for each one first, then run the walk.