Blind 75 · Trees

Lowest Common Ancestor of a Binary Search Tree

Medium

Watch the walkthrough (5:35)

Problem

The input is root, the root of a binary search tree, and two of its nodes, p and q.
In a binary search tree, every node has smaller values in its left subtree and larger values in its right subtree.
Return the lowest common ancestor of p and q: the lowest node that has both p and q in its subtree.
A node counts as being in its own subtree.

Examples

Example 1:
Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
Output: 6

Example 2:
Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
Output: 2
Explanation: an ancestor may be one of the two nodes itself.

Example 3:
Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 3, q = 5
Output: 4

Example 4:
Input: root = [2,1], p = 2, q = 1
Output: 2

Constraints

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

Prerequisites

Binary trees, and recursion over them: solve the children, combine, return. The base case is almost always the empty tree.
Depth-first order (pre, in, post) and breadth-first by level — and knowing which one a problem is really asking for.

How to think about it

1. Walk Until the Values Split Optimal

Intuition

In a search tree the values themselves say which way to go. While both targets are smaller than the current node, the ancestor must be left; while both are larger, right. The first node where they disagree — or that equals one of them — is the deepest node with both below it. No recursion, no parent pointers, and no general-tree LCA algorithm: the ordering is the whole answer.

Algorithm

1. Start at the root.
2. Both values smaller: go left.
3. Both values larger: go right.
4. Anything else: this node is the lowest common ancestor.

Time & Space

Time O(h) — one root-to-node walk. Space O(1).

2. The Same Walk, by Recursion

Intuition

The same walk, each step a call: while both values are on one side of the node, the answer is the same question asked of that side's child; where they part, or the node is p or q, it is this node. The first approach does it with one pointer in a loop. The time is the same, a node a level; the calls still open are the price.

Algorithm

1. Start at the root.
2. Both values smaller: go left.
3. Both values larger: go right.
4. Anything else: this node is the lowest common ancestor.

Time & Space

Time O(h) — one root-to-node walk. Space O(h) for the calls still open.