Lowest Common Ancestor

35 min · lowestCommonAncestor()

Two people in a family tree can share many ancestors. The answer you want is the shared one closest to them, not the oldest name at the top.

You're given a binary tree whose node values are unique, plus two different values p and q that both occur in the tree. Return the value of their lowest common ancestor (LCA): the deepest node whose subtree contains both targets.

A node belongs to its own subtree. That means when p is an ancestor of q, the answer is p itself, and the same rule works in the other direction.

A few ground rules:

  • This is a general binary tree, not necessarily a binary search tree.
  • You receive target values rather than node references, and you return the ancestor's integer value.
  • The tree is displayed as a level-order array, with null marking a missing child.

Constraints

  • 2 <= node count <= 10_000
  • All node values are unique.
  • -2_147_483_648 <= node.val <= 2_147_483_647
  • p != q
  • Both p and q are present in the tree.

Hints

Trace both routes

First find the path of values from the root to p, then the path from the root to q. Where do those two paths stop agreeing?

Ask each subtree what it found

In a recursive search, a subtree can report p, report q, report an ancestor already found below it, or report nothing.

One target on each side

When the left and right recursive calls both report a node, the current node is the first place where the two targets meet. Return it upward unchanged.

Follow-up

How would you preprocess a tree once so you could answer a large stream of LCA queries without scanning the whole tree every time?

Visible cases

Examples

Example 1

ready
Input
root = [
  3,
  5,
  1,
  6,
  2,
  0,
  8,
  null,
  null,
  7,
  4
]
p = 5
q = 1
Expected
3
Why
5 and 1 first meet at the root value 3

Example 2

ready
Input
root = [
  3,
  5,
  1,
  6,
  2,
  0,
  8,
  null,
  null,
  7,
  4
]
p = 5
q = 4
Expected
5
Why
a target can be the ancestor: 5 already contains 4 below it

Example 3

ready
Input
root = [
  1,
  2,
  null,
  3
]
p = 2
q = 3
Expected
2
Why
2 lies directly on the path from the root to 3

Interview signal

Asked at

AmazonMetaMicrosoft
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite