Lowest Common Ancestor of a Binary Search Tree

medium

Given the root of a binary search tree and two node values p and q (both guaranteed to exist, all values unique), return the value of their lowest common ancestor (LCA) — the deepest node that has both as descendants (a node is a descendant of itself).

The tree is given in level-order (breadth-first), using null for missing children.

Hints

Use the BST ordering instead of the general tree-LCA recursion.
If both values are smaller than the node, go left; if both larger, go right.
The first node where they split (or one equals the node) is the LCA.

Common doubts

It's the deepest node that still has p on one side and q on the other (or is one of them), which is exactly the definition of the lowest common ancestor.
The ordering lets you descend one path in O(height) with O(1) space, instead of searching both subtrees.
Then that node is an ancestor of the other value and is the LCA — the 'split' branch handles it.

Interview follow-ups

Without ordering you recurse into both subtrees and return the node where the two finds meet (LeetCode 236).
Depth(p) + depth(q) - 2*depth(LCA), each found by a BST descent.

Fun facts

  • The LCA descent is the point where a search for p and a search for q would first diverge.
  • This is the cleanest example of a BST turning an O(n) tree problem into an O(height) walk.

Asked at

AmazonMicrosoftFacebook
Frequently Sometimes Occasionally
Example 1
Input: root = [6, 2, 8, 0, 4, 7, 9], p = 2, q = 8
Output: 6
2 is in the left subtree and 8 in the right, so they split at the root.
Example 2
Input: root = [6, 2, 8, 0, 4, 7, 9], p = 2, q = 4
Output: 2
4 is a descendant of 2, and a node is its own ancestor.
Constraints

- The number of nodes is in the range [2, 10^5] - -10^9 <= Node.val <= 10^9 - All Node.val are unique - p and q exist in the BST

Solve this problem →