A tree has n nodes labeled 0..n−1 and the given undirected edges. Choosing any node as the root gives a rooted tree with some height. Return all roots that give the minimum height, in any order.
The best roots are the center of the longest path. Peel off all leaves layer by layer, like an onion. The last one or two nodes standing are the centers.
1function findMinHeightTrees(n: number, edges: number[][]): number[] {2if (n <= 2) return Array.from({ length: n }, (_, i) => i);3const adj: Set<number>[] = Array.from({ length: n }, () => new Set());4for (const [a, b] of edges) { adj[a].add(b); adj[b].add(a); }5let leaves = adj.flatMap((s, i) => (s.size === 1 ? [i] : [])), remaining = n;6while (remaining > 2) {7remaining -= leaves.length;8const next: number[] = [];9for (const leaf of leaves) {10const [nb] = adj[leaf];11adj[nb].delete(leaf);12if (adj[nb].size === 1) next.push(nb);13}14leaves = next;15}16return leaves;17}
Initial leaves: [0,2,5,6].
Space: play/pause · ←/→: step