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, p and q, return their lowest common ancestor. A node is an ancestor of another node when you can reach that node by walking down from it, child after child, and the node you reach is its descendant. The lowest common ancestor is the deepest node that has both p and q as descendants, where a node counts as a descendant of itself.

Example 1
Input: root = [3, 5, 1, 6, 2, 0, 8, null, null, 7, 4], p = 5, q = 1
Output: 3
Example 2
Input: root = [3, 5, 1, 6, 2, 0, 8, null, null, 7, 4], p = 5, q = 4
Output: 5
Explanation: 4 is below 5, and 5 counts as its own descendant.
Solution

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 a missing child. The root 3 has two children, 5 and 1. Below 5 are 6 and 2, and below 1 are 0 and 8. The two nulls say that 6 has no children, so the last two values, 7 and 4, hang below 2. Nodes with no children, here 6, 7, 4, 0 and 8, are called leaves.

For p = 5 and q = 1, walk down from the root to each of them: 3 then 5, and 3 then 1. The two walks share only 3, so 3 is the answer. For p = 5 and q = 4 the walks are 3, 5 and 3, 5, 2, 4. They share 3 and 5, and the deeper of the two, 5, is the answer.

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, p and q sit on different sides: one below its left child and the other below its right child. Or the answer is p or q itself, with the other one somewhere below it.

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 p = 6 and q = 4.

The tree of Example 1 with p = 6 and q = 4. The leaves 6 and 4 report themselves, 7, 0 and 8 report nothing, node 2 reports 4, node 1 reports nothing. Node 5 gets 6 from the left and 4 from the right, so it is the split point and reports 5, and the root 3 returns 5.

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 p and q on different sides. So 5 reports itself, and the root 3, hearing 5 from the left and nothing from the right, returns 5.

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 p or q itself, with the other one below it, and that node is the answer.

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 null. null means "nothing found below me". A node means one of three things: p, q, or the answer, already found further down. A parent does not need to know which of these it got, only whether it got anything.

Stopping at p or q

When should a call stop without asking its children? When it reaches an empty spot, it returns null. When it reaches p or q, it returns that node and does not look further down.

Is it safe to skip the part below p? Suppose q is down there, as in Example 2, where p is 5 and q, 4, sits below it. Then no other part of the tree holds either node, so every other call reports nothing, and 5 is passed up unchanged to the root. That is the right answer. If q is elsewhere instead, its own report meets the report of p at the split point.

The check whether a node is p compares node objects, not values. It asks whether this is the very node that was passed in, which still works if two nodes happen to hold the same value.

Combining the two reports

What does a node do with the reports from its left and right child? If both are not null, p is on one side and q on the other, so this node is the split point and returns itself. If only one side found something, the node passes that report up unchanged. If neither did, it reports null too.

Alternative: keeping both walks

The two walks down from the root also give an answer. Search the tree for p and record the nodes on the way down, then do the same for q, and compare the two lists from the front. The last node they share is the answer. This also takes time in proportion to the number of nodes, but it searches the tree twice and stores two paths, while the reports need one search and no lists.

Java Solution

The method lowestCommonAncestor works in these steps:

  1. First, if root, the node this call looks at, is null, or is p or q itself, return root without looking further down.
  2. Otherwise, call the method on root.left and keep its report in left, then call it on root.right and keep that report in right.
  3. If left and right are both not null, return root: it is the split point.
  4. Otherwise, return whichever of left and right is not null, or null if both are.

Around the method, a small TreeNode class holds a value and two children, build makes a tree from the row-by-row array, and find looks up a node by its value, so main can pass nodes rather than numbers.

The main method runs both examples, the pair 6 and 4 from the picture, the pair 7 and 4 below node 2, the far-apart pair 7 and 8, and a chain 1, 2, 3 in which q is the root.

Java
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:

Output
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 from 6 to 7 and the fourth line answers 2, because 7 and 4 are the two children of 2, so 2 now hears from both sides first.

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], where 1 is the root, 2 is its left child and 3 is below 2. Since q is 1, the very first call stops at the root and returns 1.

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.val and q.val with root.val to pick a side. The tree here is not ordered that way. Run on the tree of Example 1, that shortcut returns 3 for 6 and 2 instead of 5, and for 7 and 4 it walks off the tree and throws NullPointerException.

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 p and q are far apart, like 7 and 8, every node gets one.
  • 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 LCA of a BST.