Skip to content
AI360Xpert
Beta
Difficulty: MediumTrees

Lowest Common Ancestor of a Binary Tree

Problem in Plain English

Return the deepest node that is an ancestor of both given nodes in an arbitrary binary tree. A node counts as its own ancestor, and the result must be the original node object.

Problem Statement

Given the root of a binary tree and two distinct nodes p and q that exist in it, return their lowest common ancestor. The lowest common ancestor is the deepest node whose subtree contains both targets.

A node is a descendant of itself, so the answer may be p or q. This tree has no binary-search ordering: compare node identity, not values or left/right value ranges.

Constraints

  • 2 <= number of nodes <= 10^5
  • -10^9 <= Node.val <= 10^9; node values are unique.
  • p != q; both node objects exist in the tree.

Examples

Example 1

Input
root = [3,5,1,6,2,0,8,null,null,7,4], p = node 5, q = node 1
Output
node 3

The targets are in different root subtrees, so neither subtree contains both. Their first shared ancestor is the original root object 3.

Example 2

Input
root = [1,2], p = node 1, q = node 2
Output
node 1

In this minimum-size tree, the root is itself p and also the parent of q. A target may be the answer.

Example 3

Input
root = [3,5,1,6,2,0,8,null,null,7,4], p = node 5, q = node 4
Output
node 5

The path from 4 goes through 2 and then 5. Since 5 counts as its own ancestor, the lowest shared ancestor is 5, not 3.

Intuition

Two nodes share the upper portion of their paths from the root. Walking upward from 5 and 1 in Example 1 reaches 3 first on both paths. Remember each node’s parent, mark the ancestors of p, then climb from q until its path first touches those marks. That first intersection is deeper than every later shared ancestor.

Approaches

Iterative Parent Map

Optimal

Solution Details

Reveal Iterative Parent Map: intuition, complexity, and code

Hints

Hint 1
Picture the two paths from the root; where do they separate?
Hint 2
A parent map lets you follow either path backward without recursion.
Hint 3
Mark every ancestor of p, including p. The first marked object encountered while climbing from q is the answer.

Edge Cases

  • One target is the root, or is an ancestor of the other: return that target.
  • Targets in opposite root subtrees have the root as their LCA.
  • A 100,000-node chain requires explicit traversal storage rather than recursion.

Common Mistakes and Interview Tips

  • Applying BST value comparisons to an arbitrary binary tree skips valid subtrees.
  • Returning a new node with the right value fails the node-identity contract.
  • Excluding p from its own ancestor set misses an ancestor-target answer.
  • Stopping when only one target is discovered leaves the other parent path incomplete.

Key Takeaway

A parent map turns a rooted structure into upward paths. Their first intersection from either target gives the deepest shared ancestor without relying on value ordering.