Minimum Height Trees
You are given an undirected tree with n nodes labelled 0 to n - 1, described by a list edges where edges[i] = [a, b] connects nodes a and b. The edges are guaranteed to form a tree: the graph is connected and has no cycles.
Any node can be picked up and treated as the root. The height of the resulting rooted tree is the number of edges on the longest path from the root down to a leaf.
Return the labels of every node that, when chosen as the root, gives the smallest possible height. The labels may be returned in any order.
Example 1
Example 2
Example 3
Constraints
1 <= n <= 2 · 104edges.length == n - 10 <= a, b < nanda != b- All pairs are distinct and the edges form a tree
Pattern Path · Graphs: Ordering & Union-Find · problem 141 of 169
Start simple
Run a BFS from every node to measure the height with that node as root and keep the minimum: O(n²) time.
The key idea
The height of a tree rooted at r is the distance from r to the farthest node. The farthest node from anywhere lies at one end of a longest path (the diameter) of the tree, so the best root is the node, or pair of adjacent nodes, in the exact middle of that path. A diameter with an even number of edges has one middle node; an odd one has two.
Finding that middle directly is fiddly, so peel the tree instead. Put every leaf (degree 1) in a queue and remove them all in one round, decrementing their neighbours' degrees. Neighbours whose degree drops to 1 become the next round's leaves. Each round shortens every longest path by one edge at each end, so the centre is never removed early, and it is all that remains when at most two nodes are left.
This is Kahn's topological-sort idea applied to an undirected tree, working from the outside in. Each node and edge is processed a constant number of times, so the whole process is linear.
Handle n == 1 separately: there are no edges and node 0 is the answer.
Complexity
- Time:
O(n) - Space:
O(n)
Python
class Solution:
def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
if n <= 2:
return list(range(n))
neighbours = [set() for _ in range(n)]
for a, b in edges:
neighbours[a].add(b)
neighbours[b].add(a)
leaves = [node for node in range(n) if len(neighbours[node]) == 1]
remaining = n
# Peel off one whole layer of leaves at a time until the centre is left.
while remaining > 2:
remaining -= len(leaves)
next_leaves = []
for leaf in leaves:
parent = neighbours[leaf].pop()
neighbours[parent].remove(leaf)
if len(neighbours[parent]) == 1:
next_leaves.append(parent)
leaves = next_leaves
return leaves
JavaScript
var findMinHeightTrees = function(n, edges) {
if (n <= 2) return Array.from({ length: n }, (_, i) => i);
const neighbours = Array.from({ length: n }, () => new Set());
for (const [a, b] of edges) {
neighbours[a].add(b);
neighbours[b].add(a);
}
let leaves = [];
for (let node = 0; node < n; node++) {
if (neighbours[node].size === 1) leaves.push(node);
}
let remaining = n;
// Peel off one whole layer of leaves at a time until the centre is left.
while (remaining > 2) {
remaining -= leaves.length;
const nextLeaves = [];
for (const leaf of leaves) {
const [parent] = neighbours[leaf];
neighbours[leaf].delete(parent);
neighbours[parent].delete(leaf);
if (neighbours[parent].size === 1) nextLeaves.push(parent);
}
leaves = nextLeaves;
}
return leaves;
};
What the interviewer is checking
The interviewer is looking for the insight that the answer is the centre of the tree, and for a clean layer-by-layer leaf-trimming BFS rather than n separate searches.
Mistakes to avoid
- Forgetting the single-node case, where there are no edges and no leaves of degree 1.
- Stopping when one node is left instead of when at most two are left; the answer can have two nodes.
- Removing leaves one at a time instead of a whole layer at a time, which can strip the wrong side first.
Follow-ups to expect
- Can there ever be three answers? (No: a diameter's middle is one or two nodes.)
- How would you find the diameter itself? (Two BFS passes from any node.)
- What if edges had weights? (Centre on weighted diameter; trim by distance.)
In real software
Choosing where to place a server, hub or root switch in a tree-shaped network so that the worst-case hop count to any node is as small as possible is exactly this problem.