LeetCode #235 Medium

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 p sits above q, the answer is p.
  • 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.
Constraints
  • 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.
bsttree
Open on LeetCode ↗
02

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.

How to spot this pattern

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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def lowestCommonAncestor(self, root, p, q):
▶3 node = root
▶4 while node:
▶5 if p.val < node.val and q.val < node.val:
▶6 node = node.left
▶7 elif p.val > node.val and q.val > node.val:
▶8 node = node.right
▶9 else:
▶10 return node
662288004477993p 35q 5targets 3 and 5 → start at the root
node—
p, q3, 5
The shaded band on the number line runs from 3 to 5, the two targets. Each node sits directly above its own value, so a node inside the band lies between the targets. The walk starts at the root, which is an ancestor of every node.
662288004477993p 35q 53 and 5 are both below 6 → go left
node6
p, q3, 5
Both targets are smaller than 6, so both sit in its left subtree; the band lies wholly left of the dashed line. A common ancestor lower than 6 exists on that side, so move left.
662288004477993p 35q 53 and 5 are both above 2 → go right
node2
p, q3, 5
Both targets are larger than 2, so both sit in its right subtree; the band lies wholly right of the dashed line. Move right to get closer to them.
662288004477993p 35q 54 sits between 3 and 5 → return 4
node4
p, q3, 5
The dashed line falls inside the band: one target is in the left subtree of 4 and the other in the right. Any lower node holds only one of them, so 4 is the answer.
05

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.

▶1class Solution:
▶2 def lowestCommonAncestor(self, root, p, q):
▶3 if p.val < root.val and q.val < root.val:
▶4 return self.lowestCommonAncestor(root.left, p, q)
▶5 if p.val > root.val and q.val > root.val:
▶6 return self.lowestCommonAncestor(root.right, p, q)
▶7 return root
06

Common pitfalls

Using <= in the move tests

✗ Wrong
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.right
✓ Right
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.right

With <=, 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

✗ Wrong
return self.lowestCommonAncestor(root.left, p, q)
✓ Right
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.

07

Edge cases

One target is an ancestor of the other, e.g. p = 2, q = 4

At 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.

08

Complexity

Time
O(h)
Space
O(1)
h is the height of the tree: about log n when it is balanced, up to n when it is a chain. Each step moves down one level. The recursive version uses O(h) stack space.
09

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.