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, p and q, return their lowest common ancestor. That is the deepest node that has both p and q at or below it, so a node counts as an ancestor of itself. Both p and q are in the tree. The tree is written row by row, with null for a missing child.

Example 1
Input: root = [6, 2, 8, 0, 4, 7, 9, null, null, 3, 5], p = 2, q = 8
Output: 6
Example 2
Input: root = [6, 2, 8, 0, 4, 7, 9, null, null, 3, 5], p = 2, q = 4
Output: 2
Solution

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 itself.

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.

The example tree with root 6. The left subtree of 6 holds 2, 0, 4, 3 and 5, all below 6, and the right subtree holds 8, 7 and 9, all above 6. For p = 2 and q = 4, both are below 6, so the walk goes left to 2, which is p itself, so the answer is 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 p, so none of them can be an ancestor of p. That makes 2 the deepest ancestor the two nodes share.

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 p or q is on. The search would have to look in both subtrees of every node, and could visit all the nodes of the tree. With the order, each step rules out a whole subtree, so the walk only touches the nodes on one path from the root.

Moving down

When should the walk move down? Only when p and q are on the same side. If both values are smaller than the current node's value, both nodes are in its left subtree, and so is their lowest common ancestor. If both are larger, the same holds for the right subtree.

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 < and >, so an equal value never counts as being on a side. The walk cannot run off the bottom of the tree, because p and q are in it and the walk always heads toward them.

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 works in these steps:

  1. First, set a variable node to root. It marks where the walk is.
  2. Then repeat a while (true) loop. In each pass, if both p.val and q.val are smaller than node.val, move node to node.left.
  3. Otherwise, if both are larger than node.val, move node to node.right.
  4. In any other case, the two values part at node, or one of them is node, so return node.

Around the method sit a small TreeNode class, a build method that makes a tree from its row-by-row form, and a find method that fetches the node holding a value. The main method runs both examples, then other pairs from the same tree (two leaves, the same node passed twice, a pair that includes the root) and a tree of only two nodes.

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

Output
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. Both values are below 6, so the walk goes to 2, and there they part: 0 is below 2 and 5 is above it. The leaves 3 and 5 part one level lower, at 4, which is why that line ends in 4.

In p = 3, q = 3 -> 3 the two nodes are the same, and the answer is that node. In p = 9, q = 6 -> 6, q is the root, so the walk stops before moving at all. The last line uses the tree [2, 1], where 1 is the left child of 2, and the answer is the root 2.

The strict tests matter. With <= and >= in both tests instead, Example 2 returns 3. At 2, the second test sees 2 >= 2 and 4 >= 2, so the walk moves right to 4 and then left to 3, which is not an ancestor of 2 at all.

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 node, with no recursion and no stack, whatever the size or height of the tree.

When the values are in no order, the search has to look in both subtrees: see Lowest Common Ancestor of a Binary Tree.