Problem 235 · LeetCode 235(opens in a new tab)
Lowest Common Ancestor of a Binary Search Tree
MediumBinary search trees
You are given the root of a binary search tree: every value in a node's left subtree is smaller than the node, and every value in its right subtree is bigger. You are also given two different nodes of that tree, p and q.
Return their lowest common ancestor: the deepest node that has both p and q somewhere beneath it. A node counts as being beneath itself, so if p sits under q, the answer is q.
Example 1
Input: root = [20, 10, 30, 5, 15, 25, 35, null, null, 12, 18], p = 12, q = 18 Output: 15 Why: 12 and 18 are the two children of 15
2 more examples and the constraints
Example 2
Input: root = [20, 10, 30, 5, 15, 25, 35, null, null, 12, 18], p = 10, q = 12 Output: 10 Why: 12 is below 10, and 10 counts as its own ancestor
Example 3
Input: root = [4, null, 9], p = 9, q = 4 Output: 4 Why: 9 hangs under 4, the root
Constraints
- 2 ≤ number of nodes ≤ 100,000
- Values are distinct and between −1,000,000,000 and 1,000,000,000
pandqare different nodes, and both are in the tree
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Search the whole treeO(n)
- Walk down the BSTO(h)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a balanced tree of 100,000 nodes | Verdict |
|---|---|---|---|
| Search the whole tree | O(n) | Works on any tree; wastes the order | |
| Walk down the BST | O(h) | Best; one path from the root |
n = number of nodes, h = height of the tree (about 17 when balanced, up to n when it is a chain).
Edge cases to test
- One node is the ancestor of the other. p = 10, q = 12 in Example 1 gives 10: the walk stops when it reaches p itself.
- Split at the root. p = 5, q = 35 gives the root, 20, on the very first comparison.
- A chain-shaped tree. The height can be n, so prefer the loop over recursion to avoid a deep call stack.
- p bigger than q. Nothing says p < q. Check both values against the node, not just one.
Common mistakes
- Using
<=and>=in the comparisons, so the walk steps past a node that is p or q itself. - Assuming p is the smaller value and comparing only one of them per side.
- Searching the whole tree like a plain binary tree and never using the ordering.
How to talk through it
- 1Clarify. Are values distinct? Are both nodes always in the tree? Can one be the ancestor of the other?
- 2Give the general answer. The binary-tree LCA recursion works but visits every node: O(n).
- 3Use the order. Both smaller: go left. Both bigger: go right. Otherwise they split at this node.
- 4Code the loop. Write it iteratively and say it runs in O(h) time and O(1) space.
- 5Test out loud. Try the split at the root and the case where p is above q.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?