Minimum Height Trees

BFS from all leaves inward, peeling layers; the last 1 or 2 nodes form the centroid set.

Medium
Time O(n) Space O(n)
LeetCode
4 min read
graph bfs topology tree

Problem#

A tree (connected acyclic graph) has n nodes. Return all roots that minimize the resulting tree’s height.

Examples#

  • 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].

Constraints#

  • 1 <= n <= 2 * 10^4.

Approach#

The optimal roots are the tree’s centroid(s) — one or two nodes equidistant from all leaves. Compute by topological peeling: repeatedly remove all leaves until ≤2 nodes remain.

Solution#

Minimum Height Trees
class Solution {
public:
vector<int> findMinHeightTrees(int n, vector<vector<int>>& edges) {
if (n == 1) return {0};
vector<vector<int>> adj(n);
vector<int> deg(n, 0);
for (auto& e : edges) {
adj[e[0]].push_back(e[1]);
adj[e[1]].push_back(e[0]);
++deg[e[0]]; ++deg[e[1]];
}
queue<int> q;
for (int i = 0; i < n; ++i) if (deg[i] == 1) q.push(i);
int remaining = n;
while (remaining > 2) {
int sz = q.size();
remaining -= sz;
while (sz--) {
int u = q.front(); q.pop();
for (int v : adj[u]) {
if (--deg[v] == 1) q.push(v);
}
}
}
vector<int> ans;
while (!q.empty()) { ans.push_back(q.front()); q.pop(); }
return ans;
}
};

Editorial#

A tree has at most 2 centroids. Peeling leaves layer by layer collapses both endpoints of the longest paths toward the middle; the last surviving layer is the centroid set. n == 1 is special — the single node is the only candidate.

Complexity#

  • Time: O(n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.