LeetCode #236 Medium

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 p is above q, the answer is p.
  • 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.

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 tree.
treedfsrecursion
Open on LeetCode ↗
02

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

How to spot this pattern

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.

03

Approach

Try it first

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?

1

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.

2

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.

3

Decide at this node

Look at the two results:

  • both are nodes: p and q are on different sides, so root is 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: return None.
4

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def lowestCommonAncestor(self, root, p, q):
▶3 if not root or root is p or root is q:
▶4 return root
▶5 left = self.lowestCommonAncestor(root.left, p, q)
▶6 right = self.lowestCommonAncestor(root.right, p, q)
▶7 if left and right:
▶8 return root
▶9 return left or right
tree5returned value35p1q620874find p = 5 and q = 1
p5
q1
Start. The search begins at the root. Every call returns one node, or none: a target it found, or the answer once it is known. The badge next to a node will show what its call returned.
tree5returned value35p1q620874at 3: not a target → search left, then right
root3
3 is not a target. Nothing tells us which side holds p or q, so the call searches the left subtree, then the right one, and decides only after both answer.
tree5returned value355p1q6208745 is p → return 5, skip below
root5
returns5
5 is p, so this call returns it at once and does not look below it. If the other target is underneath, 5 is already the answer; if not, the answer is higher up. Either way nothing below can change it.
tree5returned value355p11q6208741 is q → return 1, skip below
root1
returns1
1 is q, so this call returns it at once and does not look below it. If the other target is underneath, 1 is already the answer; if not, the answer is higher up. Either way nothing below can change it.
tree5returned value3355p11q6208745 from the left, 1 from the right → 3 (answer)
left5
right1
returns3
Both sides answered: 5 is in the left subtree and 1 in the right one. The targets split here, so 3 is the deepest node holding both, the lowest common ancestor. It returns itself.
05

Common pitfalls

Returning as soon as the left side finds something

✗ Wrong
left = self.lowestCommonAncestor(root.left, p, q)
if left:
    return left
✓ Right
left = self.lowestCommonAncestor(root.left, p, q)
right = self.lowestCommonAncestor(root.right, p, q)
if left and right:
    return root

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

06

Complexity

Time
O(n)
Space
O(h)
One DFS that visits each node at most once. h is the height of the tree: about log n when balanced, n in the worst case.
07

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.