Lowest Common Ancestor of a Binary Search Tree
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
Given a binary search tree and two of its nodes p and q, return their lowest common ancestor (LCA).
Understand the problem
- A binary search tree (BST) is a binary tree with an ordering rule: every value in a node's left subtree is smaller than the node, and every value in its right subtree is larger. (The beginner guide covers this.)
- An ancestor of a node is any node on the path from the root down to it: its parent, its parent's parent, and so on. A node also counts as its own ancestor.
- A common ancestor of
pandqis a node that is an ancestor of both. The root always is. - The lowest common ancestor is the deepest one: the point where the paths from the root to
pand toqsplit apart.
6
/ \
2 8
/ \ / \
0 4 7 9
/ \
3 5Example 1
Input: p = 2, q = 8
Output: 62 is on the left of 6, and 8 is on the right. The paths split at 6.
Example 2
Input: p = 2, q = 4
Output: 24 is below 2, and 2 counts as its own ancestor, so the answer is 2 itself.
Example 3
Input: p = 3, q = 5
Output: 4Both are children of 4.
How the tests work: trees are written level by level with null for a missing child. The tests give p and q as values; your function receives the actual nodes, and the node you return is checked by its value.
Constraints
2 <= number of nodes <= 10^5- All values are unique, and
pandqboth exist in the tree.
Hints
Stuck? Open one hint at a time. Each one gives away a little more than the last.
The idea in one sentence
Walk down from the root, going left while both values are smaller and right while both are larger; the first node where they split up is the answer.
The naive approach (and why it's slow)
Find the path from the root to p, find the path from the root to q, then compare the two paths and take the last node they share. This works for any binary tree, but it finds two full paths and needs memory to store them. In a BST we can do much better.
The key insight
In a BST, the values tell you which way to go. At any node with value v:
p and q compared with v | What it means | Action |
|---|---|---|
| both smaller | both live in the left subtree, so their LCA does too | go left |
| both larger | both live in the right subtree | go right |
one smaller and one larger, or one of them is v | the paths to them split here (or one ends here) | this is the LCA |
The split point is the answer because it's the last node on the path to both: one step further and the paths go different ways.
Step by step
Using the tree from the description:
p = 3, q = 5:
| Node | Compare | Action |
|---|---|---|
6 | 3 < 6 and 5 < 6 | go left |
2 | 3 > 2 and 5 > 2 | go right |
4 | 3 < 4 but 5 > 4 | split → 4 |
p = 2, q = 4:
| Node | Compare | Action |
|---|---|---|
6 | 2 < 6 and 4 < 6 | go left |
2 | p is this node | split → 2 |
The code
The reference solution is below, with comments on every important line.
How fast is it?
- Time: O(h), where
his the tree's height: we walk one path down. That's O(log n) for a balanced tree. - Memory: O(1). Just one pointer, no recursion.
Common mistakes
- Searching the whole tree. That ignores the BST ordering, which is the whole point of the problem.
- Forgetting that a node is its own ancestor. If
pis aboveq, the answer isp. The "otherwise, return" branch handles this automatically. - Mixing up
<and>in the two conditions. Both must be smaller to go left, both larger to go right.
Going deeper
In a plain binary tree (no ordering), the values give no direction, so you search both sides: if the current node is p or q, return it; otherwise recurse left and right, and the node where both sides found something is the LCA. That's O(n) instead of O(h). It's a common follow-up question.
Reference solution
/**
* @param {TreeNode} root
* @param {TreeNode} p
* @param {TreeNode} q
* @return {TreeNode}
*/
export default function lowestCommonAncestor(root, p, q) {
let node = root
while (node) {
// Both smaller: both live in the left subtree, so their LCA does too.
if (p.val < node.val && q.val < node.val) node = node.left
// Both larger: both live in the right subtree.
else if (p.val > node.val && q.val > node.val) node = node.right
// They split here (or one of them IS this node): this is the lowest common ancestor.
else return node
}
return null
}export default function lowestCommonAncestor(
root: TreeNode | null,
p: TreeNode,
q: TreeNode,
): TreeNode | null {
let node = root
while (node) {
// Both smaller: both live in the left subtree, so their LCA does too.
if (p.val < node.val && q.val < node.val) node = node.left
// Both larger: both live in the right subtree.
else if (p.val > node.val && q.val > node.val) node = node.right
// They split here (or one of them IS this node): this is the lowest common ancestor.
else return node
}
return null
}def lowest_common_ancestor(root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
node = root
while node:
# Both smaller: both live in the left subtree, so their LCA does too.
if p.val < node.val and q.val < node.val:
node = node.left
# Both larger: both live in the right subtree.
elif p.val > node.val and q.val > node.val:
node = node.right
# They split here (or one of them IS this node): this is the lowest common ancestor.
else:
return node
return None