LCA in BST
Intermediate · 8 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
The lowest common ancestor of two nodes is the closest shared parent in the family tree. In a search tree you find it by walking down from the top and stopping at the first node where the two values go in different directions.
Practical use cases
- Web app: Shared category of two products. A comparison page lets a shopper pick two products and shows "Both belong to: Mobile Accessories". The categories form a tree, and walking down from the top until the two products part ways finds that shared category. The label appears instantly, with no need to list every parent of both items.
- Web app: Who is the common manager of two employees?. An HR portal has a button "Find common manager" for two selected employees. Starting at the top of the chart, the code goes down as long as both people are in the same branch, and the first split point is their shared boss. Escalations then go to the right person without anyone searching the chart by hand.
- System: File systems, biology and version history. Finding the nearest common folder of two files, the closest shared ancestor of two species in an evolution chart, or the common starting point of two git branches are all the same question. Each can be answered by walking down from the top and watching where the paths split, which is why this idea has so many homes.
The story: The Crossroads of House 4 and House 7
Mira lived at house 4 and her friend Kabir at house 7 in a colony whose lanes branched like a BST. Both wanted to meet at the nearest common crossroad on their way to the main road, so nobody had to walk extra.
Grandpa Bhaskar showed them how. "Start at the main gate, number 8. Is your house number smaller than 8? Both of yours are. So you both are in the left colony. Go left. At crossroad 3: both houses are bigger than 3, so go right together. At crossroad 6: Mira's house, 4, is smaller; Kabir's house, 7, is bigger. Now you must part ways. This crossroad is where your paths split!"
That meeting point is the lowest common ancestor (LCA). In a general tree finding it is hard work, but in a BST the numbers themselves tell you the direction. You keep walking down while both targets are on the same side, and stop at the first node that is between them (or is one of them).
How to spot this problem, and where you need it
You have two items in a hierarchy and need the nearest thing that contains or leads to both of them, such as a shared category, manager or folder.
Signs you need it
- The feature says "common parent", "shared category", "closest shared boss", or "nearest common folder".
- You are building two long lists of parents, one per item, and comparing them to find where they meet.
- The data is a binary search tree, so the values themselves tell you whether to go left or right.
Where to use it in a project
- Category and breadcrumb logic in shops that compare or merge two product listings.
- Org chart tools that route approvals to the nearest shared manager of two people.
The solution
Start at the top node. If both values are smaller than the current node, move left. If both are bigger, move right. The first node where one value is on one side and the other value is on the other side, or where the node equals one of the values, is the lowest common ancestor. You never walk back up and you never build lists.
Payoff: Before: build two parent lists of 20 items each and compare. After: a single walk of at most one node per level, found in a few steps.
Explain it like I am 8
Two cousins trace their way back up the family tree. The first grandparent they share is their lowest common ancestor. In a BST you do not even go up; you walk down from the top until the two cousins' numbers fall on different sides.
How it works, step by step
- Start at the root with the two keys
pandq. - If both are smaller than the current node, move to the left child.
- If both are bigger, move to the right child.
- Otherwise (they split, or one of them equals the current node), the current node is the LCA.
The code in four languages
PHP
<?php
class Node {
public ?Node $left = null;
public ?Node $right = null;
public function __construct(public int $val) {}
}
function insert(?Node $n, int $v): Node {
if ($n === null) return new Node($v);
if ($v < $n->val) $n->left = insert($n->left, $v);
else $n->right = insert($n->right, $v);
return $n;
}
// Assumes both $p and $q are in the tree
function lca(?Node $root, int $p, int $q): ?int {
$cur = $root;
while ($cur !== null) {
if ($p < $cur->val && $q < $cur->val) $cur = $cur->left; // both on the left
elseif ($p > $cur->val && $q > $cur->val) $cur = $cur->right; // both on the right
else return $cur->val; // paths split here
}
return null;
}
$root = null;
foreach ([8, 3, 10, 1, 6, 14, 4, 7, 13] as $v) $root = insert($root, $v);
echo 'lca(4, 7) = ', lca($root, 4, 7), PHP_EOL; // 6
echo 'lca(1, 7) = ', lca($root, 1, 7), PHP_EOL; // 3
echo 'lca(4, 13) = ', lca($root, 4, 13), PHP_EOL; // 8
echo 'lca(6, 7) = ', lca($root, 6, 7), PHP_EOL; // 6 (one is the ancestor of the other)JavaScript
class Node {
constructor(val) { this.val = val; this.left = null; this.right = null; }
}
function insert(n, v) {
if (n === null) return new Node(v);
if (v < n.val) n.left = insert(n.left, v);
else n.right = insert(n.right, v);
return n;
}
// Assumes both p and q are in the tree
function lca(root, p, q) {
let cur = root;
while (cur !== null) {
if (p < cur.val && q < cur.val) cur = cur.left; // both on the left
else if (p > cur.val && q > cur.val) cur = cur.right; // both on the right
else return cur.val; // paths split here
}
return null;
}
let root = null;
for (const v of [8, 3, 10, 1, 6, 14, 4, 7, 13]) root = insert(root, v);
console.log('lca(4, 7) = ' + lca(root, 4, 7)); // 6
console.log('lca(1, 7) = ' + lca(root, 1, 7)); // 3
console.log('lca(4, 13) = ' + lca(root, 4, 13)); // 8
console.log('lca(6, 7) = ' + lca(root, 6, 7)); // 6 (one is the ancestor of the other)Java
public class Main {
static class Node {
int val;
Node left, right;
Node(int val) { this.val = val; }
}
static Node insert(Node n, int v) {
if (n == null) return new Node(v);
if (v < n.val) n.left = insert(n.left, v);
else n.right = insert(n.right, v);
return n;
}
// Assumes both p and q are in the tree
static Integer lca(Node root, int p, int q) {
Node cur = root;
while (cur != null) {
if (p < cur.val && q < cur.val) cur = cur.left; // both on the left
else if (p > cur.val && q > cur.val) cur = cur.right; // both on the right
else return cur.val; // paths split here
}
return null;
}
public static void main(String[] args) {
Node root = null;
for (int v : new int[]{8, 3, 10, 1, 6, 14, 4, 7, 13}) root = insert(root, v);
System.out.println("lca(4, 7) = " + lca(root, 4, 7)); // 6
System.out.println("lca(1, 7) = " + lca(root, 1, 7)); // 3
System.out.println("lca(4, 13) = " + lca(root, 4, 13)); // 8
System.out.println("lca(6, 7) = " + lca(root, 6, 7)); // 6 (one is the ancestor of the other)
}
}Go
package main
import "fmt"
type Node struct {
val int
left, right *Node
}
func insert(n *Node, v int) *Node {
if n == nil {
return &Node{val: v}
}
if v < n.val {
n.left = insert(n.left, v)
} else {
n.right = insert(n.right, v)
}
return n
}
// lca assumes both p and q are in the tree.
func lca(root *Node, p, q int) (int, bool) {
cur := root
for cur != nil {
if p < cur.val && q < cur.val {
cur = cur.left // both on the left
} else if p > cur.val && q > cur.val {
cur = cur.right // both on the right
} else {
return cur.val, true // paths split here
}
}
return 0, false
}
func main() {
var root *Node
for _, v := range []int{8, 3, 10, 1, 6, 14, 4, 7, 13} {
root = insert(root, v)
}
a, _ := lca(root, 4, 7)
b, _ := lca(root, 1, 7)
c, _ := lca(root, 4, 13)
d, _ := lca(root, 6, 7)
fmt.Println("lca(4, 7) =", a) // 6
fmt.Println("lca(1, 7) =", b) // 3
fmt.Println("lca(4, 13) =", c) // 8
fmt.Println("lca(6, 7) =", d) // 6 (one is the ancestor of the other)
}Time: O(h) · Extra space: O(1). One walk down from the root; no recursion or parent links needed.
Watch out for
- Treating it like a general tree and searching both sides. In a BST the values decide the direction.
- Forgetting the case where one key is itself the ancestor of the other: it is then the answer.
- Not checking that both keys exist in the tree; the loop above assumes they do.
Quick check
- At a node, both keys are smaller. Where do we go?
- Right
- Left
- Stop
- LCA of 1 and 7 in our tree?
- 3
- 8
- 6
- When do we stop and return the current node?
- When we reach a leaf
- When both keys are bigger
- When the keys are on different sides, or one equals the node