Lowest Common Ancestor of a Binary Tree (LeetCode 236): Solution and Explanation

Medium
Tree
Depth First Search
Binary Tree

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.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

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

  1. Define dfs(node). If node is None, return None.
  2. If node.val equals p or q, return node immediately without searching below it.
  3. Recurse into the left child to get left and into the right child to get right.
  4. If both left and right are non-null, the targets are split across this node, so return node.
  5. Otherwise return whichever of left or right is non-null, or None if neither is.
  6. 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
  1. dfs(3) does not match, so it recurses left into 5, which also does not match and recurses further.
  2. At 5, the left call dfs(6) matches p and returns node 6.
  3. The right call goes to 2. Its left child 7 finds nothing and returns None, and its right child 4 matches q and returns node 4, so node 2 passes node 4 upward.
  4. Back at 5, left is node 6 and right is node 4. Both are non-null, so node 5 returns itself.
  5. At the root 3, the right subtree (1, 0, 8) finds nothing and returns None, so 3 passes node 5 upward.
  6. 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).val

Time and space complexity

Time

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.

Space

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 p or q. 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.