Minimum Height Trees
Difficulty: Medium · Pattern: Graphs (BFS / DFS) · LeetCode #310
A tree with n nodes (labeled 0..n−1) is given by its edges. Rooting it at different nodes gives different heights. Return all roots that give the minimum height, in any order.
Examples
text
n = 4, edges = [[1,0],[1,2],[1,3]] → [1]
n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]] → [3,4]Hints
- Rooting at every node and running BFS each time is O(n²).
- The best roots are the centers of the tree, the middle of its longest path. There are always 1 or 2 of them.
- Remove all current leaves, then the new leaves, and so on, like peeling an onion.
Approach
Topological trimming (BFS from the leaves):
- Compute each node's degree, and put all leaves (degree 1) in a queue.
- While more than 2 nodes remain, remove the current layer of leaves. Decrement their neighbors' degrees, and the neighbors that drop to degree 1 form the next layer.
- The 1 or 2 remaining nodes are the answer.
Why does it work? Each round shortens every longest path by 2 (one leaf from each end), so the process converges on its middle. Handle n == 1 → [0].
Complexity
Time: O(n). Space: O(n).
Python solution
def findMinHeightTrees(n, edges):
if n <= 2:
return list(range(n))
adj = [set() for _ in range(n)]
for a, b in edges:
adj[a].add(b)
adj[b].add(a)
leaves = [i for i in range(n) if len(adj[i]) == 1]
remaining = n
while remaining > 2:
remaining -= len(leaves)
nxt = []
for leaf in leaves:
nb = adj[leaf].pop()
adj[nb].discard(leaf)
if len(adj[nb]) == 1:
nxt.append(nb)
leaves = nxt
return leavesJavaScript solution
function findMinHeightTrees(n, edges) {
if (n <= 2) return [...Array(n).keys()];
const adj = Array.from({ length: n }, () => []), deg = new Array(n).fill(0);
for (const [a, b] of edges) { adj[a].push(b); adj[b].push(a); deg[a]++; deg[b]++; }
let leaves = [];
for (let i = 0; i < n; i++) if (deg[i] === 1) leaves.push(i);
let remaining = n;
while (remaining > 2) {
remaining -= leaves.length;
const next = [];
for (const leaf of leaves) for (const nb of adj[leaf]) if (--deg[nb] === 1) next.push(nb);
leaves = next;
}
return leaves;
}