Skip to content
Decoder

Lowest Common Ancestor of a Binary Tree

Medium

Problem

Given the root of a binary tree (an ordinary one, not a search tree) and two values p and q that are both in it, return the value of their lowest common ancestor: the deepest node that has both p and q somewhere in its subtree. A node is part of its own subtree, so a node can be its own ancestor.

Trees in the examples are written in level order (top to bottom, left to right), with null for a missing child, the same way the tests build them.

Example 1

root = [3, 5, 1, 6, 2, 0, 8, null, null, 7, 4]

Example 2

Input
p = 5, q = 1
Output
3

Example 3

Input
p = 5, q = 4
Output
5
Why
5 is above 4

Example 4

Input
p = 7, q = 4
Output
2

Constraints

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

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.