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 nn - 1edges[a, b]ab
Example 1
Output: [1]
Explanation: rooted at 1 the height is 1; rooted anywhere else it is 2.
Example 2
Output: [3,4]
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]
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.
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]baab
Each set is a HashSet
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
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
- First, if
is 1, returnn right away, since a single node has no edges.[0] - Build the adjacency list
, a list ofadj empty sets, onen per node. Then a loop overHashSet adds each end of every edge to the other end's set.edges - Collect the first layer: a loop over all nodes puts each node whose set has size 1 into the list
.leaves - Set
toremaining . Whilen is greater than 2, subtractremaining from it and start an empty list,leaves.size() , for the next layer.nextLeaves - Inside, a loop over
takes each leaf's only neighbour,leaves , withnb . It removes the leaf from the set ofadj.get(leaf).iterator().next() , and if that set now has size 1, addsnb tonb .nextLeaves - After each round,
becomes the newnextLeaves . When the while loop ends,leaves holds the one or two middle nodes, and the method returns it.leaves
The main
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:
[1]
[3, 4]
[0]
[0, 1]
[2]
[2]
Example 1 gives [1][3, 4][0][0, 1]remaining
The path 0 - 1 - 2 - 3 - 4 gives [2][2]
Why does the loop check remaining > 2remaining > 1> 1[1]NoSuchElementExceptioniterator().next()
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