Lowest Common Ancestor of a Binary Tree
Find the deepest node of a binary tree that has two given nodes in its subtree, in one recursive pass.
Given the root of a binary tree and two of its nodes, pqpq
Example 1
Output: 3
Example 2
Output: 5
Explanation: 4 is below 5, and 5 counts as its own descendant.
The Idea
A family tree is the everyday version of this problem. Your parents, grandparents and great-grandparents are your ancestors, and you share some of them with a cousin. The closest one you share, perhaps a grandmother, is your lowest common ancestor: lowest because family trees, like these trees, are drawn with the oldest generation at the top.
The array in the examples lists the tree row by row, with null
For pqpq
Writing out both walks works, but it means searching the tree once for each node and keeping the paths. Could one trip through the tree spot the answer directly? Think about what makes the answer node special. Seen from it, pqpq
So let every node report to its parent what it found below it, starting from the leaves. Look at the picture below, which uses the same tree with pq
The leaves 6 and 4 are the nodes we are looking for, so each one reports itself. The leaves 7, 0 and 8 report nothing. Node 2 hears nothing from 7 and hears 4 from its right, so it passes the 4 up and reports 4. Node 1 heard nothing from either child, so it reports nothing.
Now look at node 5, labelled as the split point. It gets 6 from the left and 4 from the right, which can happen at only one node: the deepest one with pq
That is the key insight: the answer is the first node, on the way up, that hears from both sides. When no node hears from both sides, as in Example 2, the one report that reaches the root is pq
Solution Approach
Turning the reports into code means settling three things: what each node's report is, when a search can stop early, and how a node combines the reports of its two children. Keeping the two walks from the root, the slower way described above, comes last as an alternative.
What a report is
How does a node get its children's reports? The method calls itself on the left child and on the right child, and each of those calls does the same for its own children. A method that calls itself on smaller parts of the input like this is called recursive.
Each call returns a node or nullnullpq
Stopping at p or q
When should a call stop without asking its children? When it reaches an empty spot, it returns nullpq
Is it safe to skip the part below pqpqqp
The check whether a node is p
Combining the two reports
What does a node do with the reports from its left and right child? If both are not nullpqnull
Alternative: keeping both walks
The two walks down from the root also give an answer. Search the tree for pq
Java Solution
The method lowestCommonAncestor
- First, if
, the node this call looks at, isroot , or isnull orp itself, returnq without looking further down.root - Otherwise, call the method on
and keep its report inroot.left , then call it onleft and keep that report inroot.right .right - If
andleft are both notright , returnnull : it is the split point.root - Otherwise, return whichever of
andleft is notright , ornull if both are.null
Around the method, a small TreeNodebuildfindmain
The mainq
import java.util.ArrayDeque;
import java.util.Queue;
public class LowestCommonAncestor {
static class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) { this.val = val; }
}
public static TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || root == p || root == q) {
return root; // nothing here, or one of the two itself
}
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if (left != null && right != null) {
return root; // p on one side, q on the other
}
return left != null ? left : right; // pass up whatever was found, or null
}
// builds a tree from the 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.remove();
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, so main can pass nodes rather than numbers
static TreeNode find(TreeNode node, int val) {
if (node == null || node.val == val) {
return node;
}
TreeNode inLeft = find(node.left, val);
return inLeft != null ? inLeft : find(node.right, val);
}
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(3, 5, 1, 6, 2, 0, 8, null, null, 7, 4);
run(root, 5, 1);
run(root, 5, 4);
run(root, 6, 4);
run(root, 7, 4);
run(root, 7, 8);
TreeNode chain = build(1, 2, null, 3);
run(chain, 3, 1);
}
}
Running it prints:
p = 5, q = 1 -> 3
p = 5, q = 4 -> 5
p = 6, q = 4 -> 5
p = 7, q = 4 -> 2
p = 7, q = 8 -> 3
p = 3, q = 1 -> 1
Look at the second line: 5 and 4 give 5, Example 2's answer, even though the search stopped at 5 and never reached 4. The third line is the picture: 6 and 4 meet at 5. Move p
On the fifth line, 7 and 8 sit in opposite halves of the tree, so only the root 3 hears from both sides. The last line uses the chain [1, 2, null, 3]q
A binary search tree keeps smaller values to the left of each node and larger ones to the right, and for it a quicker method compares p.valq.valroot.valNullPointerException
Complexity
Each call does a fixed amount of work besides its two recursive calls, so the cost depends on how many nodes get a call and how deep the calls nest.
- Time: O(n), because each of the n nodes gets at most one call, and when
andp are far apart, like 7 and 8, every node gets one.q - Space: O(h), because the calls still waiting at any moment form one path down from the root, so there are at most h of them when the longest root-to-leaf path has h nodes. That is about log n when every row is full, and n for a chain.
In a binary search tree the values show which way to go, so no full search is needed: see