Minimum Height Trees

Pick the roots that make a tree as short as possible, by trimming its leaves until only the middle is left.

A tree has n nodes, labelled 0 to n - 1, and is given as a list edges, where each edge [a, b] joins nodes a and b. Between any two nodes there is exactly one path. Any node can be chosen as the root, and the height is then the number of edges from the root to the node farthest from it. Return every root that gives the smallest height, in any order.

Example 1
Input: n = 4, edges = [[1,0],[1,2],[1,3]]
Output: [1]
Explanation: rooted at 1 the height is 1; rooted anywhere else it is 2.
Example 2
Input: n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]
Output: [3,4]
Solution

The Idea

Picture six villages joined by five roads, laid out like Example 2. Village 3 has roads to 0, 1, 2 and 4, and one more road joins 4 and 5. You want to build a fire station in one village, so that the farthest village is as few roads away as possible. Each village is a node, each road is an edge, and the village with the station is the root.

Count the roads from each choice. From 3, villages 0, 1, 2 and 4 are one road away and 5 is two roads away, so the height is 2. From 4 the height is also 2, because 0, 1 and 2 are two roads away through 3. From 0 the farthest village is 5, three roads away, and 1, 2 and 5 also give 3. So the answer is [3, 4]. Example 1 works the same way: node 1 is joined to every other node, so only root 1 gives height 1.

Measuring the height from every node finds the answer, but it walks the whole tree once for each node. Can we see where the best roots are without measuring? Look at which nodes end up farthest away. They always sit at the outside of the tree, on a node with only one neighbour, called a leaf. In Example 2 the leaves are 0, 1, 2 and 5.

A leaf is a poor root when the tree has three or more nodes. Its only neighbour reaches every other node one edge sooner than the leaf does, so moving the root one step inward always lowers the height. So take the leaves away. Look at the picture below.

The tree of Example 2: node 3 joined to 0, 1, 2 and 4, and 4 joined to 5. The leaves 0, 1, 2 and 5 are drawn in orange. After removing the leaves, 3 and 4 are left, and they are the answer.

On the left is the tree of Example 2, with the leaves 0, 1, 2 and 5 in orange. Removing them leaves 3 and 4, on the right, labelled as the middle of the tree. That is exactly the answer we counted by hand.

Removing every leaf at once lowers the height from each remaining node by exactly one, because each farthest node was a leaf. The best roots of the smaller tree are therefore the best roots of the whole tree. In a bigger tree the removal creates new leaves, so we keep peeling, one layer at a time, until only the middle is left.

Solution Approach

Turning the peeling into code means settling four things: why measuring every root is too slow, how to store the tree, how to remove one layer of leaves, and when to stop.

Measuring every root

What does the simple way cost? It measures the height from each node with a breadth-first search, BFS for short. From the root, a BFS visits its neighbours, then their neighbours, one ring of nodes at a time, and the number of rings is the height. One BFS visits all n nodes, so n of them take about n2 steps. Peeling removes each node once, so it takes about n steps.

Storing the tree

How do we find a node's neighbours quickly? The list of edges does not say, so we turn it into an adjacency list: for every node, the set of nodes it is joined to. For Example 2 that is 3 → {0, 1, 2, 4}, 4 → {3, 5}, 5 → {4}, and 0, 1 and 2 → {3}. Each edge [a, b] adds b to the set of a and a to the set of b.

Each set is a HashSet, so taking a removed leaf out of its neighbour's set is a single step. The size of a set is then how many neighbours the node still has, its degree, and a node with degree 1 is a leaf.

Removing one layer of leaves

How does one round of peeling work? The first layer is every node with degree 1. A leaf's only neighbour is the one entry in its set. Removing the leaf takes it out of that neighbour's set, and a neighbour whose degree drops to 1 has just become a leaf, so it joins the next layer.

Take the path 0 - 1 - 2 - 3 - 4. The first layer is 0 and 4. Removing them leaves 1 and 3 with one neighbour each, so they form the second layer, and removing those leaves 2. A whole layer goes at once so that every path is shortened at both ends evenly. Removing leaves one by one from the left would eat the path from that side and end off centre.

When to stop

How many nodes can the middle have? Example 2 shows it can be two: 3 and 4 are each other's only neighbour, and both give height 2. Two nodes joined by an edge are both leaves, so one more round would remove both and leave nothing. Three nodes can never be the end, because in a tree they form a line, and the one in the centre beats the two ends. So a count, remaining, tracks how many nodes are left, and peeling stops once it is 2 or less.

A tree with one node has no edges and no leaves at all. Its single node 0 is the answer, so the method returns it before building anything.

Java Solution

The method findMinHeightTrees works in these steps:

  1. First, if n is 1, return [0] right away, since a single node has no edges.
  2. Build the adjacency list adj, a list of n empty sets, one HashSet per node. Then a loop over edges adds each end of every edge to the other end's set.
  3. Collect the first layer: a loop over all nodes puts each node whose set has size 1 into the list leaves.
  4. Set remaining to n. While remaining is greater than 2, subtract leaves.size() from it and start an empty list, nextLeaves, for the next layer.
  5. Inside, a loop over leaves takes each leaf's only neighbour, nb, with adj.get(leaf).iterator().next(). It removes the leaf from the set of nb, and if that set now has size 1, adds nb to nextLeaves.
  6. After each round, nextLeaves becomes the new leaves. When the while loop ends, leaves holds the one or two middle nodes, and the method returns it.

The main method runs both examples, a single node, two nodes joined by one edge, the path 0 - 1 - 2 - 3 - 4, and a seven-node tree that needs two rounds of peeling.

Java
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class MinimumHeightTrees {

    public List<Integer> findMinHeightTrees(int n, int[][] edges) {
        if (n == 1) {
            return List.of(0);                        // one node, no edges: it is the root
        }
        List<Set<Integer>> adj = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            adj.add(new HashSet<>());
        }
        for (int[] e : edges) {
            adj.get(e[0]).add(e[1]);
            adj.get(e[1]).add(e[0]);
        }

        List<Integer> leaves = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            if (adj.get(i).size() == 1) {
                leaves.add(i);
            }
        }
        int remaining = n;
        while (remaining > 2) {                       // the middle is 1 or 2 nodes
            remaining -= leaves.size();
            List<Integer> nextLeaves = new ArrayList<>();
            for (int leaf : leaves) {
                int nb = adj.get(leaf).iterator().next();   // a leaf's only neighbour
                adj.get(nb).remove(leaf);
                if (adj.get(nb).size() == 1) {
                    nextLeaves.add(nb);               // nb has just become a leaf
                }
            }
            leaves = nextLeaves;
        }
        return leaves;
    }

    public static void main(String[] args) {
        MinimumHeightTrees m = new MinimumHeightTrees();
        System.out.println(m.findMinHeightTrees(4, new int[][] {{1, 0}, {1, 2}, {1, 3}}));
        System.out.println(m.findMinHeightTrees(6,
                new int[][] {{3, 0}, {3, 1}, {3, 2}, {3, 4}, {5, 4}}));
        System.out.println(m.findMinHeightTrees(1, new int[][] {}));
        System.out.println(m.findMinHeightTrees(2, new int[][] {{0, 1}}));
        System.out.println(m.findMinHeightTrees(5,
                new int[][] {{0, 1}, {1, 2}, {2, 3}, {3, 4}}));
        System.out.println(m.findMinHeightTrees(7,
                new int[][] {{0, 1}, {1, 2}, {2, 3}, {3, 4}, {2, 5}, {5, 6}}));
    }
}

Running it prints:

Output
[1]
[3, 4]
[0]
[0, 1]
[2]
[2]

Example 1 gives [1] and Example 2 gives [3, 4], as expected. The single node returns [0] from the early check. The two-node tree prints [0, 1] without peeling at all, because remaining starts at 2 and the while loop never runs.

The path 0 - 1 - 2 - 3 - 4 gives [2] after the two rounds described earlier. The last line, also [2], comes from a tree where node 2 has three arms: 1 then 0, 3 then 4, and 5 then 6. The first round removes 0, 4 and 6, the second removes 1, 3 and 5. From 2 every node is at most two edges away, while every other root gives height 3 or 4.

Why does the loop check remaining > 2 and not remaining > 1? With > 1, Example 1 still prints [1], but Example 2 throws NoSuchElementException. After the first round, 3 and 4 form the next layer, and the loop runs once more. Removing 3 empties the set of 4, so when the loop reaches 4, iterator().next() on its empty set fails.

Complexity

Each node joins a layer once and is removed once, and each removal changes a single neighbour's set.

  • Time: O(n), because building the sets handles each of the n - 1 edges twice, and each of the n nodes is removed once with one constant-time set removal.
  • Space: O(n), because the neighbour sets hold two entries for each of the n - 1 edges, and the two leaf lists hold at most n nodes between them.

Taking out, layer by layer, the nodes that nothing else holds in place is also how Topological Sort orders tasks, with Kahn's algorithm.