Skip to content
Decoder

Lowest Common Ancestor in a BST

Medium

Problem

Given the root of a binary search tree and two values p and q that both exist in it, return the value of 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.

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 = [6, 2, 8, 0, 4, 7, 9, null, null, 3, 5]

Example 2

Input
p = 2, q = 8
Output
6

Example 3

Input
p = 2, q = 4
Output
2
Why
2 is an ancestor of 4, and of itself

Example 4

Input
p = 3, q = 5
Output
4

Constraints

  • 2 <= number of nodes <= 10^5
  • -10^9 <= Node.val <= 10^9
  • All values are distinct, p != q, and both 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.