Minimum height trees solution explained
Minimum Height Trees asks which nodes of an undirected tree give the shortest tree when chosen as the root. The answer is the tree's center, always one node or two adjacent nodes, and you find it by peeling leaves: remove every current leaf, which creates new leaves, and repeat until at most two nodes remain. That is O(n) time and O(n) space, against O(n²) for running a BFS from every node.
By Evin JohnPublished 8 min read
The problem in plain words
You get a number n and a list of n - 1 edges that connect nodes 0 to n - 1 into a tree: connected, no cycles, edges without direction. Any node can be picked as the root, and the height is then the longest distance from that root to any node. Return every node whose choice as root gives the smallest possible height, in any order.
n = 7, edges = 0-1, 1-2, 2-3, 3-4, 2-5, 5-6
0 - 1 - 2 - 3 - 4
|
5 - 6
Answer: [2] (rooted at 2, every node is at most 2 steps away)
Add node 7 and edge 6-7 (n = 8): answer [2, 5]
Rooted at 2 or at 5, the height is 3; every other root is worse.In the second graph the longest path has five edges (for example 0, 1, 2, 5, 6, 7), so it has two middle nodes, 2 and 5. Rooting at either one leaves at most three steps to the far end.
Why it is asked
The direct approach is obvious and too slow, and the fast one needs an insight about the shape of trees. Interviewers use it to see if you can reason about the longest path, and whether you recognize that peeling leaves layer by layer is the same queue-of-degree-one-nodes technique as topological sorting. It also checks graph basics: adjacency lists, degrees and handling of tiny inputs.
Brute force: BFS from every node
For each node, run a breadth-first search and record the largest distance found; that is the height when rooted there. Keep the nodes with the smallest height. Each BFS is O(n) on a tree, so the total is O(n²). It is a clean reference for testing, and a fine first statement, but it repeats almost the same work n times.
from collections import deque
def roots_by_bfs(n, edges):
graph = [[] for _ in range(n)]
for a, b in edges:
graph[a].append(b)
graph[b].append(a)
def height_from(start): # BFS: farthest distance from start
dist = [-1] * n
dist[start] = 0
queue = deque([start])
while queue:
v = queue.popleft()
for w in graph[v]:
if dist[w] < 0:
dist[w] = dist[v] + 1
queue.append(w)
return max(dist)
heights = [height_from(v) for v in range(n)]
best = min(heights)
return [v for v in range(n) if heights[v] == best]The insight: the answer is the middle of the longest path
Take the longest path in the tree, its diameter, with d edges. Any root's height is at least half of d, rounded up, because one end of that path is at least that far away. The middle node of the path, or either of the two middle nodes when d is odd, achieves exactly that bound. So the answer is one node when d is even and two adjacent nodes when d is odd, never more.
You do not need to find the diameter explicitly. Removing all current leaves shortens every longest path by one at each end and keeps its middle in place. Repeat, and the last one or two nodes standing are the middle. Stop when two or fewer nodes remain; going further would delete the answer.
Optimal: peel leaves layer by layer
def min_height_roots(n, edges):
if n <= 2:
return list(range(n)) # one node, or two joined nodes: all are centers
neighbors = [set() for _ in range(n)]
for a, b in edges:
neighbors[a].add(b)
neighbors[b].add(a)
leaves = [v for v in range(n) if len(neighbors[v]) == 1]
remaining = n
while remaining > 2:
remaining -= len(leaves)
next_leaves = []
for leaf in leaves:
parent = neighbors[leaf].pop() # a leaf has exactly one neighbor
neighbors[parent].remove(leaf)
if len(neighbors[parent]) == 1:
next_leaves.append(parent)
leaves = next_leaves
return sorted(leaves)function minHeightRoots(n, edges) {
if (n <= 2) return [...Array(n).keys()];
const graph = Array.from({ length: n }, () => []);
const degree = new Array(n).fill(0);
for (const [a, b] of edges) {
graph[a].push(b);
graph[b].push(a);
degree[a]++;
degree[b]++;
}
let leaves = [];
for (let v = 0; v < n; v++) if (degree[v] === 1) leaves.push(v);
let remaining = n;
while (remaining > 2) {
remaining -= leaves.length;
const next = [];
for (const leaf of leaves) {
for (const w of graph[leaf]) {
degree[w]--; // an already removed leaf drops to 0 here, never back to 1
if (degree[w] === 1) next.push(w);
}
}
leaves = next;
}
return leaves.sort((x, y) => x - y);
}Trace the first example. Leaves are 0, 4 and 6. Removing them leaves 1, 2, 3 and 5; nodes 1, 3 and 5 now have one neighbor each, so they are the next layer. Four nodes remain, which is more than two, so remove that layer too. One node, 2, remains: that is the answer. In the second example the layers are {0, 4, 7}, then {1, 3, 6}, which leaves 2 and 5.
There is a second linear approach that mirrors the insight directly: BFS from any node to find the farthest node a, BFS from a to find the farthest node b while recording parents, then walk the path from b back to a and take its middle one or two nodes. Both are O(n). Leaf peeling is shorter to code and harder to get wrong under pressure.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| BFS from every node | O(n²) | O(n) |
| Peel leaves until two or fewer remain | O(n) | O(n) |
| Two BFS runs to find the diameter, take its middle | O(n) | O(n) |
Edge cases to test
- n = 1 with no edges: the answer is [0]. The leaf loop would find no leaves, so handle it first.
- n = 2: both nodes are leaves and both are answers.
- A path of even length (odd number of nodes): one center. Odd length: two.
- A star, one hub joined to everything: the hub alone, after one round.
- Edges listed in any order and in either direction.
Common mistakes
- Stopping when one node remains instead of two or fewer, which over-peels when there are two centers.
- Counting the remaining nodes after building the next layer rather than subtracting the layer just removed.
- Skipping the small-input guard: a single node has no neighbor at all, so a scan for one-neighbor leaves finds nothing and returns an empty list instead of [0].
- Rebuilding degrees from scratch each round, which turns the linear algorithm quadratic.
- Assuming the answer is a single node and returning only one of the two centers.
How to explain it out loud
Fictional example
- Candidate
- The direct way is a BFS from every node to get its height. That is n searches of size n, so quadratic.
- Candidate
- But the best root has to be in the middle of the longest path; anything else is farther from one end of it. So the answer is one node, or two neighbors.
- Candidate
- I can find that middle by repeatedly removing all leaves. Each round trims both ends of every longest path equally, and I stop at two or fewer nodes.
- Candidate
- Every node and edge is handled once: linear time and space. I need to special-case a single node, which has no leaves.
Related problems
The layer-by-layer queue here is the one in graph traversal patterns, where Kahn's topological sort peels zero-indegree nodes the same way. For rooted trees, Binary Tree Preorder Traversal and Recover Binary Search Tree show the depth-first side. Grids are graphs too: Number of Islands uses BFS for a different question. The coding problems hub lists every walkthrough.
Practicing with Natively
Graph questions are often given as a drawing or an edge list on screen. During practice, Natively can read either from a screenshot on Mac or Windows, run through the peeling rounds with you, and ask why there can never be three answers. With the session transcribed, you can review whether you led with the brute force and its cost before the insight.
Questions people ask
How do you solve Minimum Height Trees?
Repeatedly remove all current leaves, nodes with one neighbor, which turns their neighbors into new leaves. Stop when two or fewer nodes remain; those nodes are the roots with minimum height.
Why does Minimum Height Trees have at most two answers?
The best roots are the middle of the tree's longest path. A path with an even number of edges has one middle node, and one with an odd number has two adjacent middle nodes.
What is the time complexity of Minimum Height Trees?
O(n) time and space with leaf peeling, compared with O(n squared) for running a breadth-first search from every node.
What are the edge cases in Minimum Height Trees?
A single node with no edges, whose answer is that node, and two connected nodes, where both are answers. Handle them before the peeling loop.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
