Lowest Common Ancestor of Binary Tree
Lowest Common Ancestor of a Binary Tree is LeetCode 236 (Medium). You are given the root of a binary 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 an ancestor of itself, so if
pis aboveq, the answer isp. - All values are unique,
p != q, and both nodes are in the tree. - The tree is not a binary search tree, so a node's value says nothing about where it is.
The tree can have 10⁵ nodes, so the target is one pass over it.
- 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 tree.
Intuition
Ask each subtree one question: which of p and q did you find? Each call answers with a node:
- None: neither target is in this subtree.
porq: this subtree holds a target, and that target is the highest one in it.- The answer: it was already found lower down.
The first node where both sides report a target is where the paths to p and q split, so it is the deepest node holding both. When p is above q, the search stops at p and never meets q. Nothing else reports, so p travels up alone and is returned, which is the right answer.
This is the "ask both children, then decide here" pattern, a post-order DFS. Reach for it whenever a node's answer depends on what its subtrees found, as in diameter of a binary tree or checking whether a tree is balanced. Here the value returned upward carries the information, so no extra flags are needed.
Approach
Before reading on: in the tree [3,5,1,6,2,0,8,null,null,7,4], which node is the answer for p = 5, q = 4? When the search reaches 5, does it need to look below it?
Stop at an empty node or a target
If root is None, return None. If root is p or q, return root without searching below it. Whether the other target is underneath or somewhere else, the answer is this node or one above it, so looking deeper cannot change it.
Search both subtrees
Call the function on root.left and on root.right. No ordering tells you which side holds a target, so both sides must be searched, and both calls must finish before this node decides anything.
Decide at this node
Look at the two results:
- both are nodes:
pandqare on different sides, sorootis the answer; return it. - one is a node: return it. It is a target still waiting for its partner, or the answer on its way up.
- both are
None: returnNone.
Why it is correct
Below the split node, each subtree holds at most one target, so it passes that target up. At the split node both sides report, and above it only one side ever does, so the split node is passed up unchanged all the way to the root.
Code in Python, C++ and Java
Common pitfalls
Returning as soon as the left side finds something
left = self.lowestCommonAncestor(root.left, p, q)
if left:
return leftleft = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if left and right:
return rootFor p = 5, q = 1 in the example tree, the left call returns 5 and the right subtree is never searched, so 5 comes back instead of 3. The case that makes this node the answer, targets on both sides, can only be seen after both calls finish.
Complexity
Lowest Common Ancestor of Binary Tree FAQ
Can the lowest common ancestor be found without recursion?
Yes. Some solutions use parent pointers instead. Walk the tree once with a stack and record each node's parent. Then collect every ancestor of p into a set and climb from q until you reach a node in that set; that node is the answer. It is O(n) time and O(n) extra space.
How is this different from the BST version?
In a binary search tree (LeetCode 235), values tell you where p and q are: if both are smaller than the node go left, if both are larger go right, otherwise this node is the answer. That is one walk down, O(h). In a plain binary tree there is no such hint, so both subtrees must be searched, O(n).
What if p or q might not be in the tree?
This solution assumes both are present. If one is missing, it returns the other one, which is wrong. LeetCode 1644 asks for that case: search the whole tree without stopping early at a target, count how many targets you actually saw, and return None unless the count is 2.