Minimum Height Trees (LeetCode 310): Solution and Explanation
You are given an undirected tree with n nodes. Choosing a node as the root gives the tree a height, the longest root-to-leaf path. Return every node whose choice as root gives the smallest possible height.
Watch it run step by step
Try your own input and write the code →Intuition
The brute force is to try each node as the root, run a BFS to measure the height, and keep the best. That is O(n) per root and O(n²) overall, too slow for tens of thousands of nodes.
Think about where a good root lives. A leaf is a terrible root, because its only path goes inward and the far side of the tree hangs off it. The best root sits in the middle of the longest path in the tree, so that the distance to the farthest leaf on either side is balanced. A path has either one middle node or two, which is why the answer always has one or two nodes.
You can find that middle without computing the longest path directly. Peel off all current leaves at once, the way you would peel an onion, layer by layer from the outside. Removing a whole layer shortens every longest path by one at each end, so the centers do not move. New leaves appear as their neighbors lose degree, and you repeat. When two or fewer nodes remain, those are the centers. This is a topological sort run from the outside in.
Approach: Topological trimming of leaves
- Handle
n == 1by returning[0], since a single node has no edges and therefore no leaves. - Build an adjacency map of sets so neighbors can be removed in O(1).
- Collect the initial leaves, nodes with exactly one neighbor.
- While more than two nodes remain, subtract the number of leaves from
remaining. - For each leaf, pop its single neighbor, remove the leaf from that neighbor's set, and if the neighbor now has exactly one neighbor, add it to
new_leaves. - Replace
leaveswithnew_leavesand repeat. When the loop ends,leavesholds the one or two centers.
Step-by-step example
n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]
- Degrees are 0:1, 1:1, 2:1, 3:4, 4:2, 5:1, so the first leaves are
[0, 1, 2, 5]. - Since 6 > 2, set
remaining = 6 - 4 = 2. Removing 0, 1 and 2 drops node 3 to one neighbor, and removing 5 drops node 4 to one neighbor. new_leavesis[3, 4]and becomesleaves.- Now
remainingis 2, so the loop stops and the function returns[3, 4]. Rooting at either gives height 2, while any other root gives at least 3.
Code: Python, Java, C++
1class Solution:
2 def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:
3 if n == 1:
4 return [0]
5
6 graph = defaultdict(set)
7 for a, b in edges:
8 graph[a].add(b)
9 graph[b].add(a)
10
11 leaves = [i for i in range(n) if len(graph[i]) == 1]
12
13 remaining = n
14 while remaining > 2:
15 remaining -= len(leaves)
16 new_leaves = []
17 for leaf in leaves:
18 neighbor = graph[leaf].pop()
19 graph[neighbor].remove(leaf)
20 if len(graph[neighbor]) == 1:
21 new_leaves.append(neighbor)
22 leaves = new_leaves
23
24 return leaves1class Solution {
2 public int[] findMinHeightTrees(int n, int[][] edges) {
3 if (n == 1) return new int[]{0};
4
5 Set<Integer>[] graph = new HashSet[n];
6 for (int i = 0; i < n; i++) graph[i] = new HashSet<>();
7 for (int[] e : edges) {
8 graph[e[0]].add(e[1]);
9 graph[e[1]].add(e[0]);
10 }
11
12 List<Integer> leaves = new ArrayList<>();
13 for (int i = 0; i < n; i++) {
14 if (graph[i].size() == 1) leaves.add(i);
15 }
16
17 int remaining = n;
18 while (remaining > 2) {
19 remaining -= leaves.size();
20 List<Integer> newLeaves = new ArrayList<>();
21 for (int leaf : leaves) {
22 int neighbor = graph[leaf].iterator().next();
23 graph[neighbor].remove(leaf);
24 if (graph[neighbor].size() == 1) newLeaves.add(neighbor);
25 }
26 leaves = newLeaves;
27 }
28
29 return leaves.stream().mapToInt(i -> i).toArray();
30 }
31}1class Solution {
2public:
3 vector<int> findMinHeightTrees(int n, vector<vector<int>>& edges) {
4 if (n == 1) return {0};
5
6 vector<unordered_set<int>> graph(n);
7 for (auto& e : edges) {
8 graph[e[0]].insert(e[1]);
9 graph[e[1]].insert(e[0]);
10 }
11
12 vector<int> leaves;
13 for (int i = 0; i < n; i++) {
14 if (graph[i].size() == 1) leaves.push_back(i);
15 }
16
17 int remaining = n;
18 while (remaining > 2) {
19 remaining -= leaves.size();
20 vector<int> newLeaves;
21 for (int leaf : leaves) {
22 int neighbor = *graph[leaf].begin();
23 graph[neighbor].erase(leaf);
24 if (graph[neighbor].size() == 1) newLeaves.push_back(neighbor);
25 }
26 leaves = newLeaves;
27 }
28
29 return leaves;
30 }
31};Time and space complexity
O(n)
Building the graph uses the n - 1 edges once, and each node is trimmed exactly once, with constant work per removed edge.
O(n)
The adjacency sets store each edge twice and the leaf lists hold at most n nodes.
Other approaches
BFS from every node (time O(n²), space O(n))
Root the tree at each node in turn and measure its height with BFS, keeping the minimum. Simple but quadratic.
Two BFS passes for the diameter (time O(n), space O(n))
BFS from any node to find the farthest node u, then BFS from u to find the farthest v while recording parents. Walk the path from u to v and return its middle one or two nodes.
Common mistakes
- Stopping when one node remains instead of when at most two remain. Trees with an even-length diameter have two centers, and trimming further would discard both.
- Decrementing
remainingwhile processing each leaf inside the loop rather than by the whole layer. Leaves must be removed in layers, or you can trim past the center. - Forgetting the
n == 1case. A single node has no edges, so it is never a leaf and the leaf list starts empty. - Using adjacency lists and recomputing degrees by length after removals without actually removing entries, which leaves stale neighbors behind.
Frequently asked questions
Why can there be at most two minimum height trees?
The best roots are the middle of the tree's longest path. A path with an odd number of nodes has one middle node and one with an even number has two, so the answer has one or two nodes.
Why does trimming leaves find the center?
Removing all leaves at once shortens every longest path by one at both ends, so its middle stays the same. Repeating until two or fewer nodes remain leaves exactly the middle.
What is the time complexity of Minimum Height Trees?
O(n). Each node is removed once and each edge is processed a constant number of times.
Is this topological sort?
It is the same idea as Kahn's algorithm, but run on an undirected tree using degree 1 instead of in-degree 0 as the condition to process a node.