Lowest Common Ancestor of a Binary Tree (LeetCode 236): Solution and Explanation
Given a binary tree with unique values and two target values p and q that both appear in it, find their lowest common ancestor: the deepest node whose subtree contains both targets. A node may be the ancestor of itself, so if one target sits under the other, the upper one is the answer.
Watch it run step by step
Try your own input and write the code →Intuition
A direct approach is to find the path from the root to p and the path from the root to q, store both, and walk them together until they diverge. The last shared node is the answer. That works in O(n) time, but it needs two searches and extra memory for the paths, and the bookkeeping is easy to get wrong.
There is a neater way to think about it. Ask each node a single question: does your subtree contain p, q, or neither? If you answer it bottom up, a node learns what its left and right subtrees found before it decides anything. When one target turns up on the left and the other on the right, this node is the first place the two paths meet, so it must be the lowest common ancestor.
That leads to a postorder DFS that returns a node rather than a boolean. A null node returns None. A node whose value matches p or q returns itself right away, because if the other target is underneath it, it is already the answer, and if not, the match still needs to be reported upward. Otherwise the node combines its children: if both sides returned something, it returns itself; if only one side did, it passes that result up. Whatever reaches the root is the answer.
Approach: Postorder DFS returning the found node
- Define
dfs(node). Ifnodeis None, return None. - If
node.valequalsporq, returnnodeimmediately without searching below it. - Recurse into the left child to get
leftand into the right child to getright. - If both
leftandrightare non-null, the targets are split across this node, so returnnode. - Otherwise return whichever of
leftorrightis non-null, or None if neither is. - Call
dfs(root)and return the value of the node it produces.
Step-by-step example
root = [3,5,1,6,2,0,8,null,null,7,4], p = 6, q = 4
dfs(3)does not match, so it recurses left into 5, which also does not match and recurses further.- At 5, the left call
dfs(6)matchespand returns node 6. - The right call goes to 2. Its left child 7 finds nothing and returns None, and its right child 4 matches
qand returns node 4, so node 2 passes node 4 upward. - Back at 5,
leftis node 6 andrightis node 4. Both are non-null, so node 5 returns itself. - At the root 3, the right subtree (1, 0, 8) finds nothing and returns None, so 3 passes node 5 upward.
- The final result is node 5, and the function returns its value 5.
Code: Python, Java, C++
1class Solution:
2 def lowestCommonAncestor(self, root: 'TreeNode', p: int, q: int) -> int:
3 def dfs(node):
4 if not node:
5 return None
6 if node.val == p or node.val == q:
7 return node
8 left = dfs(node.left)
9 right = dfs(node.right)
10 if left and right:
11 return node
12 return left or right
13 return dfs(root).val1class Solution {
2 int p, q;
3 public int lowestCommonAncestor(TreeNode root, int p, int q) {
4 this.p = p;
5 this.q = q;
6 return dfs(root).val;
7 }
8 private TreeNode dfs(TreeNode node) {
9 if (node == null) return null;
10 if (node.val == p || node.val == q) return node;
11 TreeNode left = dfs(node.left);
12 TreeNode right = dfs(node.right);
13 if (left != null && right != null) return node;
14 return left != null ? left : right;
15 }
16}1class Solution {
2public:
3 int p, q;
4 int lowestCommonAncestor(TreeNode* root, int p, int q) {
5 this->p = p;
6 this->q = q;
7 return dfs(root)->val;
8 }
9 TreeNode* dfs(TreeNode* node) {
10 if (!node) return nullptr;
11 if (node->val == p || node->val == q) return node;
12 TreeNode* left = dfs(node->left);
13 TreeNode* right = dfs(node->right);
14 if (left && right) return node;
15 return left ? left : right;
16 }
17};Time and space complexity
O(n)
Each node is visited at most once by the DFS, and the work per node is constant. Matching nodes cut off the search below them, which can only reduce the work.
O(h)
The recursion stack holds one frame per level of the current path, so it grows to the tree height h. A skewed tree makes that O(n).
Other approaches
Root-to-node paths (time O(n), space O(n))
Find and store the path from the root to each target, then compare the two paths from the start and return the last node they share. It is easy to reason about but needs two traversals and two path lists.
Parent pointers with an ancestor set (time O(n), space O(n))
Traverse the tree once to record each node's parent in a hash map, add every ancestor of p to a set, then walk up from q until you hit a node in that set. This is handy when you have many queries or when the tree already stores parent links.
Common mistakes
- Continuing to search below a node that matches
porq. Returning immediately is correct because the matched node is either the answer or must be reported upward either way. - Returning a boolean instead of a node. You need the actual node so the root call can report which one is the ancestor.
- Assuming the tree is a binary search tree and choosing a direction by comparing values, which gives wrong answers on an arbitrary tree.
- Forgetting that this version relies on both targets existing in the tree. If one might be missing, you must track whether each was actually found.
Frequently asked questions
Why does returning early on a match give the right answer?
If the matched node has the other target below it, the matched node is the lowest common ancestor and returning it is correct. If the other target is elsewhere, some ancestor will receive this node from one side and the other target from the other side, and that ancestor will return itself.
What is the time complexity of LCA in a binary tree?
The recursive solution is O(n) time because it visits each node at most once, and O(h) space for the recursion stack, where h is the height of the tree.
What if p or q is not in the tree?
The standard solution assumes both exist. If one may be missing, it would return the node it did find, which is wrong. To handle that case, do a full traversal that counts how many targets were found and only accept the result when both were seen.