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.
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.
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.
- 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
On a BST you don't need the general tree-LCA recursion — the ordering does the work. Compare both values to the current node: if both are smaller, the LCA is in the left subtree; if both are larger, the right; otherwise the values split here (or one equals this node), so this node is the LCA. One walk down — O(height), O(1) space.
“Are p and q guaranteed present?”
Yes, and all values are unique.
“Is a node its own ancestor?”
Yes — if p is an ancestor of q, the LCA is p.
On a BST I compare both values to the node: both smaller means go left, both larger means go right.
The first node where they split — or where one equals the node — is the lowest common ancestor.
Worked example — BST [6, 2, 8, 0, 4, 7, 9], p = 2, q = 8
6: 2 < 6 and 8 > 6 -> they split here -> LCA = 6
When p and q are on the same side, the LCA is deeper on that side.
The first node where they go different ways is their lowest common ancestor.
It's a single descent, no stack or recursion needed.
| Recursive by comparison | Iterative by comparison | |
|---|---|---|
| Idea | Recurse the side both values fall on | Loop down to the split point |
| Time | O(height) | O(height) |
| Space | O(height) | O(1) |
Both use the ordering; the iterative version is O(1) space. Full code is in the Approaches selector below.
Key takeaway
Descend the BST: both values smaller ⇒ go left, both larger ⇒ go right, otherwise this node is the LCA. O(height) time, O(1) space.
while node:
if p < node and q < node: node = node.left
elif p > node and q > node: node = node.right
else: return node