Lowest Common Ancestor of a Binary Tree

Medium

Topics
TreeDFS

You are given the root of a binary tree whose node values are all different, plus two values p and q that both appear in the tree. Return the value of their lowest common ancestor: the deepest node that has both of them in its subtree. A node counts as part of its own subtree, so if one value sits below the other, the upper one is the answer.

Unlike the search-tree version of this problem, the values follow no ordering, so you cannot tell which side to go down by comparing numbers.

Example 1

2468101214
the two targetslowest common ancestor
The answer is the deepest node that has both targets below it, 4. A post-order pass returns whichever target it found; the node that first hears back from both sides is the ancestor, and a node that is itself a target counts as its own.
Tree given in level-order (breadth-first); null marks a missing child.
Input:  root = [8,4,12,2,6,10,14], p = 2, q = 6
Output: 4

Example 2

2468101214
the two targetslowest common ancestor
Input:  root = [8,4,12,2,6,10,14], p = 6, q = 14
Output: 8

Example 3

371
the two targetslowest common ancestor
Input:  root = [1,7,null,3], p = 7, q = 3
Output: 7
Explanation: 3 is inside the subtree of 7.

Constraints

  • 2 <= number of nodes <= 10^5
  • -10^9 <= Node.val <= 10^9
  • All values are distinct.
  • p != q, and both exist in the tree.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Ask each subtree a single question: does it contain p, q, or neither? The first node, walking upwards, where the answer arrives from two different directions (left and right, or itself and one child) is where the two paths to p and q meet.

Approach

  1. Recurse post-order. An empty subtree reports nothing.
  2. If the current node is p or q, report the current node.
  3. Otherwise ask both children. If both report something, the current node is the meeting point: report it.
  4. If only one child reports, pass its report upward unchanged.
  5. The report that reaches the root is the answer.

Dry Run

tree 8 4 12 2 6 10 14
        8
      /   \
     4     12
    / \   /  \
   2   6 10  14
Without an ordering to exploit, every node asks its two subtrees "did you find
either target?" and the answers come back up:
p = 2, q = 6
      node 2 is a target, return it up
      node 6 is a target, return it up
    node 4 received a hit from BOTH sides  ->  node 4 is the LCA
      node 10 passes up nothing
      node 14 passes up nothing
    node 12 passes up nothing
  node 8 passes up the 4 it got from the left
answer 4
p = 6, q = 14
    node 4 passes up the 6
    node 12 passes up the 14
  node 8 received a hit from both sides  ->  answer 8
The return value carries two different meanings, and that overloading is the
trick: "the LCA" once found, and "one target I saw down here" before then. Both
travel up the same channel, and the node that receives a non-null from each side
is the first one that can see both -- which is the definition of lowest common
ancestor.
Note what happens at node 4 in the second case. It found the 6 and returns it
unchanged, NOT itself, because one hit is not enough. Only `left and right`
promotes a node to the answer.
The walk stops at a target without looking below it, which is correct only because
the problem guarantees both nodes exist. If q were absent, p would be reported as
the ancestor of a pair that has none.

Complexity

  • Time — O(n): every node is visited once.
  • Space — O(h): the recursion stack, up to the tree height; use an explicit stack for very deep trees.

Common Pitfalls

  • Stopping at p without looking below it is correct only because q is guaranteed to exist: if q were missing, p would be wrongly reported.
  • Recursion on a 10^5-node chain can overflow the default stack in Python and Java; an iterative parent-map walk avoids it.

Full Solution — all languages

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
class Solution:
    def lowestCommonAncestor(self, root, p, q):
        def walk(node):
            if not node:
                return None
            if node.val == p or node.val == q:
                return node
            left = walk(node.left)
            right = walk(node.right)
            if left and right:
                return node
            return left or right

        found = walk(root)
        return found.val if found else -1
SensAI
Beta
Tap the mic to stop voice mode