Lowest common ancestor
32 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)The lowest common ancestor is the deepest node shared by two targets. It powers merge bases and network routing.
Lowest common ancestor in a binary tree
The lowest common ancestor (LCA) of two nodes is the deepest node that has both of them as descendants.
The lowest common ancestor (LCA) of nodes p and q is their deepest shared ancestor. A node can be an ancestor of itself according to the standard definition. A naive brute-force method finds root-to-node paths for both targets into lists.
import java.util.List;
public class PathLca { public static void main(String[] args) { List<Integer> pathTo5 = List.of(3, 5); // root-to-node paths List<Integer> pathTo1 = List.of(3, 1); int i = 0; while (i < pathTo5.size() && i < pathTo1.size() && pathTo5.get(i).equals(pathTo1.get(i))) { i++; } System.out.println("LCA = " + pathTo5.get(i - 1)); // last node both paths share }}LCA = 3
Then it compares the two paths starting from the root index. The last node matching in both lists is the lowest common ancestor. This method works in linear time but requires extra list storage.
Trace a tree with root 3 having left child 5 and right child 1. To find the ancestor of 5 and 1, list paths [3, 5] and [3, 1]. The paths diverge immediately after node 3, so node 3 is the ancestor.
Single-pass postorder recursive algorithm
We can find the common ancestor in a single traversal without auxiliary lists. If the current node is null or equals p or q, return it immediately. Recursively inspect both the left subtree and the right subtree.
Example 1 · Optimal: one postorder pass (O(n) time, O(h) space)
public class Main { static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int val) { this.val = val; } }
static TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if (root == null || root == p || root == q) { return root; } TreeNode left = lowestCommonAncestor(root.left, p, q); TreeNode right = lowestCommonAncestor(root.right, p, q);
if (left != null && right != null) { return root; } return left != null ? left : right; }
public static void main(String[] args) { TreeNode root = new TreeNode(3); root.left = new TreeNode(5); root.right = new TreeNode(1); root.left.left = new TreeNode(6); root.left.right = new TreeNode(2);
TreeNode lca = lowestCommonAncestor(root, root.left.left, root.left.right); System.out.println("LCA of 6 and 2: " + lca.val);
TreeNode lca2 = lowestCommonAncestor(root, root.left, root.right); System.out.println("LCA of 5 and 1: " + lca2.val); }}LCA of 6 and 2: 5 LCA of 5 and 1: 3
What this code does
- Base cases return the root if it is null or matches either target.
- If both child subtrees find a target, the current node is their ancestor.
- Otherwise the non-null child result propagates up the call stack.
- Why it is faster than the path lists: it never builds or compares lists, and it stops looking below a node as soon as that node is p or q.
If both recursive calls return non-null, the current node separates p and q. Therefore, the current node is their lowest common ancestor. If only one side returns non-null, pass that non-null result upward. Trace the search when p is 5 and q is 4 inside the left child of 5. The search reaches 5 and returns 5 immediately without visiting 4. Because 5 is returned and the right child returns null, 5 correctly emerges as the ancestor.
Parent pointers and distance between two nodes
If nodes store direct parent pointers, we can walk upward like linked lists. Climb from node p to the root while inserting every visited ancestor into a set. Then climb from node q until reaching the first ancestor already in the set.
Example 2 · Alternative: parent pointers (O(h) time, O(h) space)
import java.util.HashSet;import java.util.Set;
public class Main { static class Node { int val; Node parent; Node(int val) { this.val = val; } }
static Node findLca(Node p, Node q) { Set<Node> visited = new HashSet<>(); Node curr = p; while (curr != null) { visited.add(curr); curr = curr.parent; } curr = q; while (curr != null) { if (visited.contains(curr)) { return curr; } curr = curr.parent; } return null; }
public static void main(String[] args) { Node root = new Node(1); Node child2 = new Node(2); child2.parent = root; Node child3 = new Node(3); child3.parent = root; Node child4 = new Node(4); child4.parent = child2;
Node lca = findLca(child4, child2); System.out.println("LCA of 4 and 2: " + lca.val); }}LCA of 4 and 2: 2
What this code does
- Walk upward from the first node and record every ancestor in a set.
- Walk upward from the second node until intersecting the recorded set.
- The first intersection node is the lowest common ancestor.
Example 3 · Distance Between Two Nodes
public class Main { static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int val) { this.val = val; } }
static TreeNode findLca(TreeNode root, int p, int q) { if (root == null || root.val == p || root.val == q) return root; TreeNode left = findLca(root.left, p, q); TreeNode right = findLca(root.right, p, q); if (left != null && right != null) return root; return left != null ? left : right; }
static int findDistance(TreeNode root, int val, int dist) { if (root == null) return -1; if (root.val == val) return dist; int d = findDistance(root.left, val, dist + 1); if (d != -1) return d; return findDistance(root.right, val, dist + 1); }
public static void main(String[] args) { TreeNode root = new TreeNode(1); root.left = new TreeNode(2); root.right = new TreeNode(3); root.left.left = new TreeNode(4); root.left.right = new TreeNode(5);
TreeNode lca = findLca(root, 4, 5); int d1 = findDistance(lca, 4, 0); int d2 = findDistance(lca, 5, 0); System.out.println("Distance between 4 and 5: " + (d1 + d2)); }}Distance between 4 and 5: 2
What this code does
- First locate the lowest common ancestor of the two target nodes.
- Measure distance from the common ancestor to each target separately.
- The sum of both downward distances gives the total edge count.
The distance between two tree nodes is the number of connecting edges. Compute the distance from root to p, from root to q, and from root to their ancestor. The formula is dist(p, q) = depth(p) + depth(q) - 2 * depth(ancestor). Suppose node p has depth 3 and node q has depth 2. With ancestor depth 1, distance is 3 + 2 - 2 = 3 edges.
Next step
Check your understanding
10 quick questions