Lowest Common Ancestor of a Binary Search Tree

MediumTrees

You get the root of a binary search tree, where every value in a node’s left subtree is smaller than the node and every value in its right subtree is larger. You also get two different nodes of the tree, p and q.

Return their lowest common ancestor: the deepest node that has both p and q in its subtree. A node counts as being in its own subtree, so p itself can be the answer.

On this page the tree is written in level order, top to bottom and left to right, with null where a child is missing, and p and q are written as their values. The tests find those nodes in the tree, pass the nodes to you, and read the value of the node you return.

Examples

Example 1
Input:  root = [40, 20, 60, 10, 30, null, 70, null, 15, 25], p = 15, q = 25
Output: 20

15 sits left of 20 and 25 right of it, so their paths split at 20.

Example 2
Input:  root = [40, 20, 60, 10, 30, null, 70, null, 15, 25], p = 60, q = 70
Output: 60

70 is below 60, and 60 counts as its own ancestor.

Constraints

  • The tree has 2 to 10⁵ nodes.
  • -10⁹ ≤ node.val ≤ 10⁹, and no two nodes share a value.
  • p and q are different nodes, and both are in the tree.

Stuck?

Hint 1

In a search tree the values tell you where to look: a value smaller than a node lives to its left, a larger one to its right.

Hint 2

Start at the root. If p and q are both smaller, move left; if both are larger, move right. Otherwise their paths split here, or one of them is this node, so this is the answer.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 10 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur