Lowest Common Ancestor of a Binary Tree

medium

Given the root of a binary tree and two node values p and q (both guaranteed to exist, all node values are unique), return the value of their lowest common ancestor (LCA) — the deepest node that has both p and q as descendants (a node is a descendant of itself).

The tree is given in level-order (breadth-first), using null for missing children.

Hints

Recurse; return a node when it equals p or q.
If both children return a non-null result, the current node is the split point — the LCA.
If only one child returns something, pass that result up.

Common doubts

A node is a descendant of itself, so dfs returns p as soon as it matches, and p is the LCA.
It means one target lies in the left subtree and the other in the right, so the current node is the deepest that has both as descendants.
It records the root-to-target path for each and returns the last node their paths share.

Interview follow-ups

On a BST you can walk down comparing values: go left if both targets are smaller, right if both larger, else you're at the LCA (LeetCode 235).
Preprocess with binary lifting or Euler tour + sparse table for O(log n) or O(1) per query.

Fun facts

  • The 'return match, split when both sides report' recursion is one of the most elegant tree algorithms.
  • On a BST the LCA is found without any auxiliary structure, just by comparing values on the way down.

Asked at

AmazonFacebookMicrosoftGoogle
Frequently Sometimes Occasionally
Example 1
Input: root = [3, 5, 1, 6, 2, 0, 8], p = 5, q = 1
Output: 3
5 and 1 sit in different subtrees of 3, which is their lowest common ancestor.
Example 2
Input: root = [3, 5, 1, 6, 2, 0, 8, null, null, 7, 4], p = 5, q = 4
Output: 5
4 is a descendant of 5, and a node is a descendant of itself, so the LCA is 5.
Constraints

- The number of nodes is in the range [2, 10^5] - -10^9 <= Node.val <= 10^9 - All Node.val are unique - p != q is not required; both p and q exist in the tree

Solve this problem →