Lowest Common Ancestor of a Binary Tree
Problem
Given the root of a binary tree and two distinct nodes p and q that both appear in it, return their lowest common ancestor: the deepest node whose subtree contains both p and q. A node is considered an ancestor of itself, so if one of the two nodes is above the other, the upper node is the answer.
- The tree has between 2 and 150,000 nodes; it is not ordered in any way.
- All node values are distinct.
pandqare nodes in the tree andp != q.
Examples
root = [40, 22, 61, 8, 35, 50, 93, None, None, 30, 37],p = 22,q = 61→40. The two nodes are in different subtrees of the root.- Same tree,
p = 22,q = 37→22. 37 lives under 22, so 22 is its own ancestor and the lowest common one. root = [5, 9],p = 5,q = 9→5.
Hints
- Walking down from the root, where do the paths to
pand toqdiverge? - If a subtree contains neither target it can report "nothing"; if it contains exactly one it can report which; what does a node conclude when its two children report different targets?
- Post-order DFS that returns
p,q, orNonefrom each subtree; the first node whose left and right both return non-null is the LCA, and it is passed up unchanged.
Last reviewed 8 September 2026
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.