Lowest Common Ancestor of a Binary Tree

Medium Trees AI round

root is the root of a binary tree whose nodes all hold different values. p and q are two of its nodes, or the same node twice; the examples name each node by the value it holds.

A node's subtree is the node itself and every node below it: its children, their children, and so on down. A node is a common ancestor of p and q when both are in its subtree, so the root is always one.

Return the lowest common ancestor of p and q: of all their common ancestors, the one deepest in the tree, farthest from the root. When q is in the subtree of p, that is p itself.

Example 1

Input: root = [8,3,12,null,14,5,7,null,null,1,10], p = 1, q = 7
Output: 12
83121457110

1 is in the subtree of 12, through its left child 5, and 7 is the right child of 12, so 12 holds both. The root, 8, holds them too, but 12 is deeper.

Example 2

Input: root = [8,3,12,null,14,5,7,null,null,1,10], p = 5, q = 10
Output: 5
83121457110

10 is a child of 5, and 5 is in its own subtree, so 5 itself is the deepest node that holds both.

Example 3

Input: root = [-5,10,0,null,3,-8], p = 3, q = -8
Output: -5
-51003-8

Constraints

  • 1 ≤ number of nodes ≤ 10⁵
  • -10⁹ ≤ node.val ≤ 10⁹, and no two nodes hold the same value
  • p and q are nodes of the tree, and may be the same node

More Trees

All Trees problems