Minimum Height Trees
Hard
Topics
Given a tree of n nodes labeled from 0 to n-1 with n-1 edges, return the number of nodes that could be the root of a Minimum Height Tree (MHT). A MHT is one where the longest path from root to any leaf is minimized.
Example 1
Input: n = 4, edges = [[1,0],[1,2],[1,3]] Output: 1
Example 2
Input: n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]] Output: 2
Constraints
- 1 <= n <= 2*10^4
- edges.length == n - 1
- The graph is a valid tree.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Rooting the tree at a node whose eccentricity is minimal is the definition of a centre, and a tree has exactly one or two of them. So the answer is never more than 2, which is worth saying before any code — it reframes the question from "compute n heights" to "find the centre".
Peel the tree from the outside. Remove all current leaves at once, then all the leaves of what remains, and so on. Each round strips one layer from every branch simultaneously, so the last one or two nodes standing are the deepest-buried, which is exactly the centre.
Two nodes survive when the tree's longest path has even length, one when it is odd — the centre is the middle of the diameter.
Approach
- Return 1 immediately for a single node.
- Build adjacency sets and collect every node of degree 1.
- While more than two nodes remain, remove the current leaf layer, unlink each from its neighbour, and collect the neighbours that have just become leaves.
- Return the count of nodes left standing.
Dry Run
n = 6 edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]
0 1 2
\ | /
3
|
4
|
5
degrees [1, 1, 1, 4, 2, 1]
round 0 peel leaves [0, 1, 2, 5] 6 nodes before peeling, 2 after
node 3 drops to degree 1, node 4 drops to degree 1
2 nodes remain, so the loop stops
final centres [3, 4] answer 2
n = 1 -> 1 a lone node is its own centre
n = 2 -> 2 both ends of a single edge are centresComplexity
- Time — O(n): every node is peeled once and every edge is unlinked once.
- Space — O(n) for the adjacency sets and the leaf frontier.
Common Pitfalls
- Computing the height from every root with a separate BFS. That is O(n²) — 4×10⁸ operations at the stated bound — and it is the version the peel replaces.
- Peeling one leaf at a time instead of a whole layer. The layers are what make the remaining nodes equidistant from the frontier; peeling individually can strand the wrong node.
- Looping while more than one node remains. With an even-length diameter two centres are tied, and continuing removes one of them arbitrarily.
- Forgetting the
n == 1case, where the node has degree 0 and is never collected as a leaf, so the frontier starts empty. - Using an adjacency list and deleting by value, which is O(degree) per removal and turns the peel into O(n²) on a star. Sets, or a degree counter, keep it linear.
- Claiming the answer can exceed 2. It cannot — and an interviewer will ask you to justify that, which the diameter-midpoint argument does.
Full Solution — all languages
class Solution:
def findMinHeightTreesCount(self, n, edges):
if n == 1:
return 1
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:
neighbour = adj[leaf].pop()
adj[neighbour].discard(leaf)
if len(adj[neighbour]) == 1:
nxt.append(neighbour)
leaves = nxt
return len(leaves) if leaves else remainingimport java.util.*;
class Solution {
public int findMinHeightTreesCount(int n, int[][] edges) {
if (n == 1) return 1;
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) {
remaining -= leaves.size();
List<Integer> next = new ArrayList<>();
for (int leaf : leaves) {
int neighbour = adj.get(leaf).iterator().next();
adj.get(leaf).remove(neighbour);
adj.get(neighbour).remove(leaf);
if (adj.get(neighbour).size() == 1) next.add(neighbour);
}
leaves = next;
}
return leaves.isEmpty() ? remaining : leaves.size();
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int findMinHeightTreesCount(int n, vector<vector<int>>& edges) {
if (n == 1) return 1;
vector<set<int>> adj(n);
for (auto& e : edges) {
adj[e[0]].insert(e[1]);
adj[e[1]].insert(e[0]);
}
vector<int> leaves;
for (int i = 0; i < n; i++) if (adj[i].size() == 1) leaves.push_back(i);
int remaining = n;
while (remaining > 2) {
remaining -= (int)leaves.size();
vector<int> next;
for (int leaf : leaves) {
int neighbour = *adj[leaf].begin();
adj[leaf].erase(neighbour);
adj[neighbour].erase(leaf);
if (adj[neighbour].size() == 1) next.push_back(neighbour);
}
leaves = next;
}
return leaves.empty() ? remaining : (int)leaves.size();
}
};/**
* @param {number} n
* @param {number[][]} edges
* @return {number}
*/ var findMinHeightTreesCount = function(n, edges) {
if (n === 1) return 1;
const adj = Array.from({ length: n }, () => new Set());
for (const e of edges) {
adj[e[0]].add(e[1]);
adj[e[1]].add(e[0]);
}
let leaves = [];
for (let i = 0; i < n; i++) if (adj[i].size === 1) leaves.push(i);
let remaining = n;
while (remaining > 2) {
remaining -= leaves.length;
const next = [];
for (const leaf of leaves) {
const neighbour = adj[leaf].values().next().value;
adj[leaf].delete(neighbour);
adj[neighbour].delete(leaf);
if (adj[neighbour].size === 1) next.push(neighbour);
}
leaves = next;
}
return leaves.length ? leaves.length : remaining;
};