Problem Statement

Lowest Common Ancestor of a Binary Search Tree

You are given a binary search tree, or BST. A tree is a set of nodes where each node can have a left child and a right child. A binary search tree adds one rule: for any node, every value on its left is smaller than the node, and every value on its right is larger. You are also given two nodes, p and q. The job is to find their lowest common ancestor, or LCA. An ancestor is any node you pass through on the way down to another node. The lowest common ancestor is the deepest node that has both p and q below it (including the node itself counting as below itself).

mediumTreeTreesTime: O(h) · Space: O(1)

Signals to notice

find common ancestor in a BSTboth nodes in one subtreeuse BST ordering

Brute force first

Find paths from root to each node, compare paths for the last common node. Doesn't exploit the BST property. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.

The key insight

Walk from the root: if both values are smaller, go left. If both are larger, go right. When they split (one left, one right), the current node is the LCA. Once you hold onto the right piece of information from moment to moment, the problem feels less like trial and error and more like following a shape that was there all along.

Trace it on root=[6,2,8,0,4,7,9], p=2, q=4

node=6: p=2<6 and q=4<6 -> both smaller, go left to node 2
node=2: p=2<2 is false (not both smaller) and 2>2 is false (not both larger) -> neither branch taken, fall to else
Here one target (p) equals the current node, so node 2 is an ancestor of both p and q -> this is the LCA
return node=2 (matches expected output 2)

What must stay true

In a BST, if p < node < q (or q < node < p), then node is where p and q diverge into different subtrees — that split point IS the LCA. No node deeper can be an ancestor of both. When you keep that truth intact, each local choice supports the larger solution instead of fighting it.

Shape of the loop

node = root
while node is not null:
    if p.val < node.val and q.val < node.val: node = node.left
    elif p.val > node.val and q.val > node.val: node = node.right
    else: return node   # values split (or one equals node) -> LCA

Pseudocode only — the full worked solution lives in the Solution tab.

Easy way to go wrong

Using the generic binary tree LCA algorithm (recursive, ) when the BST property gives you a simpler solution. The BST ordering is a free guide. The fix is usually to return to the meaning of each move, not just the steps themselves.

Trees Pattern