Skip to content

Lowest Common Ancestor of a Binary Tree

MediumTrees
Decode it first. Clues, constraints, pattern and plan before any code.

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.

root = [3, 5, 1, 6, 2, 0, 8, null, null, 7, 4]
p = 5, q = 1  →  3
p = 5, q = 4  →  5   (5 is above 4)
p = 7, q = 4  →  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.