Lowest Common Ancestor of a BST
Find the deepest node of a binary search tree that has two given nodes below it or is one of them.
Given the root of a binary search tree and two of its nodes, pqpqpqnull
Example 1
Output: 6
Example 2
Output: 2
The Idea
Think of a family tree. Your parents, your grandparents and everyone above them are your ancestors. Two cousins share their grandparents and everyone above, and the closest of those shared relatives is their lowest common ancestor. In a tree of numbers, the ancestors of a node are the nodes on the way from the top down to it.
Both examples use the same tree. Its top node, called the root, is 6. The root's left child is 2 and its right child is 8. Below 2 hang 0 and 4, below 4 hang 3 and 5, and below 8 hang 7 and 9.
A node's left subtree is its left child together with everything below that child, and its right subtree is the same on the right. The tree is a binary search tree: each node has at most two children, values in a node's left subtree are smaller than the node, and values in its right subtree are larger. Under 6, the left side holds 2, 0, 4, 3 and 5, all below 6, and the right side holds 8, 7 and 9, all above it.
Now list ancestors. In Example 1, the ancestors of 2 are 6 and 2, and the ancestors of 8 are 6 and 8. They share only 6, so the answer is 6. In Example 2, the ancestors of 4 are 6, 2 and 4, and those of 2 are 6 and 2. They share 6 and 2, and the deeper one, 2, is the answer, even though it is p
Do we really need to write out both lists of ancestors and compare them? The values already say which way to go from any node. Look at the picture below, which shows Example 2.
At the root, the note reads "p = 2 and q = 4 are both below 6: go left". Both nodes are inside the box labelled "left subtree of 6", so every ancestor they share, apart from 6, is in that box too. The orange arrow moves the walk to 2.
At 2 the note reads "2 is p itself: stop". Every node further down is below pp
So the answer comes from one walk down from the root. While both values lie on the same side of the current node, follow them to that side. The walk stops at the first node where they part, one going left and the other right, or where one of them is the node itself. Below that node, no single subtree holds both, so it is the lowest shared ancestor. In Example 1 the walk stops at once, because 2 is below 6 and 8 is above it.
Solution Approach
Turning the walk into code means settling three things: when to move down, when to stop, and whether to use a loop or recursion. First, though, why is the walk so short? Because of the order of the values.
Searching without the order
What if the values were in no particular order? Then nothing would tell us which side pq
Moving down
When should the walk move down? Only when pq
Stopping
When should it stop? In every other case: one value is smaller and the other larger, or one of them equals the current node's value. For that reason the two tests use strict <>pq
A loop instead of recursion
Should the method call itself on the chosen child? It could, but each call would only hand the work to one child and return that child's answer unchanged. A plain loop that keeps one variable for the current node does the same job, without a chain of calls that grows with the depth of the tree.
Java Solution
The method lowestCommonAncestor
- First, set a variable
tonode . It marks where the walk is.root - Then repeat a
loop. In each pass, if bothwhile (true) andp.val are smaller thanq.val , movenode.val tonode .node.left - Otherwise, if both are larger than
, movenode.val tonode .node.right - In any other case, the two values part at
, or one of them isnode , so returnnode .node
Around the method sit a small TreeNodebuildfindmain
import java.util.ArrayDeque;
import java.util.Queue;
public class LowestCommonAncestorBST {
static class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) { this.val = val; }
}
public static TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
TreeNode node = root;
while (true) {
if (p.val < node.val && q.val < node.val) {
node = node.left; // both are smaller: go left
} else if (p.val > node.val && q.val > node.val) {
node = node.right; // both are larger: go right
} else {
return node; // they split here, or one of them is this node
}
}
}
// Builds a tree from its row-by-row form, with null for a missing child.
static TreeNode build(Integer... values) {
TreeNode root = new TreeNode(values[0]);
Queue<TreeNode> parents = new ArrayDeque<>();
parents.add(root);
int i = 1;
while (i < values.length) {
TreeNode parent = parents.poll();
if (values[i] != null) {
parent.left = new TreeNode(values[i]);
parents.add(parent.left);
}
i++;
if (i < values.length && values[i] != null) {
parent.right = new TreeNode(values[i]);
parents.add(parent.right);
}
i++;
}
return root;
}
// Finds the node holding a value, walking down by the same smaller/larger rule.
static TreeNode find(TreeNode root, int val) {
TreeNode node = root;
while (node.val != val) {
node = val < node.val ? node.left : node.right;
}
return node;
}
static void run(TreeNode root, int p, int q) {
TreeNode lca = lowestCommonAncestor(root, find(root, p), find(root, q));
System.out.println("p = " + p + ", q = " + q + " -> " + lca.val);
}
public static void main(String[] args) {
TreeNode root = build(6, 2, 8, 0, 4, 7, 9, null, null, 3, 5);
run(root, 2, 8); // Example 1
run(root, 2, 4); // Example 2
run(root, 3, 5);
run(root, 0, 5);
run(root, 7, 9);
run(root, 3, 3);
run(root, 9, 6);
run(build(2, 1), 2, 1);
}
}
Running it prints:
p = 2, q = 8 -> 6
p = 2, q = 4 -> 2
p = 3, q = 5 -> 4
p = 0, q = 5 -> 2
p = 7, q = 9 -> 8
p = 3, q = 3 -> 3
p = 9, q = 6 -> 6
p = 2, q = 1 -> 2
Look at p = 0, q = 5 -> 2
In p = 3, q = 3 -> 3p = 9, q = 6 -> 6q[2, 1]
The strict tests matter. With <=>=
Complexity
The walk follows a single path down from the root and does a fixed amount of work at each node on it.
- Time: O(h), where h is the height of the tree (the number of steps on its longest path from the root down), because each pass of the loop moves one level down and makes at most four comparisons. In a well-balanced tree of n nodes, h grows like log n, but in a tree shaped like one long chain it is n - 1.
- Space: O(1), because the loop keeps only the variable
, with no recursion and no stack, whatever the size or height of the tree.node
When the values are in no order, the search has to look in both subtrees: see