Problem
You are given an undirected tree of n nodes labeled 0 to n-1. The height of a tree is the number of edges on the longest downward path from a chosen root. Return every root that produces a minimum-height tree.
Original: LeetCode 310: Minimum Height Trees.
Examples
Example 1
`n = 4, edges = [[1, 0], [1, 2], [1, 3]]``[1]`Example 2
`n = 6, edges = [[3, 0], [3, 1], [3, 2], [3, 4], [5, 4]]``[3, 4]`Roots can be returned in any order.
Constraints
1 <= n <= 2 * 10^4edges.length == n - 10 <= ai, bi < nai != bi- All the pairs
(ai, bi)are distinct. - The given input is guaranteed to be a tree and there will be no repeated edges.
Hints
Hint 1
The input is a tree, so it is connected and acyclic. You may return the roots in any order. There are at most two such roots.
Hint 2
The best roots sit in the middle of the longest path. Peeling leaves layer by layer finds those centroids in linear time.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. For each possible root, BFS to compute the height, then keep the minimum. That is O(n²).
Optimal. Compute degrees, start from all leaves (degree 1), and remove them level by level, reducing neighbour degrees, until two or fewer nodes remain.
Alternative. Find the diameter with two BFS passes and take the one or two middle nodes of that path.
Complexity
- Time
- O(n)
O(n) time and O(n) space, because each node and edge is processed a constant number of times.
- Space
- O(n)
Code
from collections import defaultdict, deque
def find_min_height_trees(n: int, edges: list[list[int]]) -> list[int]:
if n == 1:
return [0]
graph = defaultdict(set)
for a, b in edges:
graph[a].add(b)
graph[b].add(a)
leaves = deque(i for i in range(n) if len(graph[i]) == 1)
remaining = n
while remaining > 2:
size = len(leaves)
remaining -= size
for _ in range(size):
leaf = leaves.popleft()
nei = next(iter(graph[leaf]))
graph[nei].remove(leaf)
if len(graph[nei]) == 1:
leaves.append(nei)
return list(leaves)
if __name__ == "__main__":
assert set(find_min_height_trees(4, [[1, 0], [1, 2], [1, 3]])) == {1}
assert set(find_min_height_trees(6, [[3, 0], [3, 1], [3, 2], [3, 4], [5, 4]])) == {3, 4}
print("ok")import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class MinimumHeightTrees {
static List<Integer> findMinHeightTrees(int n, int[][] edges) {
if (n == 1) return List.of(0);
List<Set<Integer>> graph = new ArrayList<>();
for (int i = 0; i < n; i++) graph.add(new HashSet<>());
for (int[] e : edges) {
graph.get(e[0]).add(e[1]);
graph.get(e[1]).add(e[0]);
}
var leaves = new ArrayDeque<Integer>();
for (int i = 0; i < n; i++) if (graph.get(i).size() == 1) leaves.add(i);
int remaining = n;
while (remaining > 2) {
int size = leaves.size();
remaining -= size;
for (int i = 0; i < size; i++) {
int leaf = leaves.remove();
int nei = graph.get(leaf).iterator().next();
graph.get(nei).remove(leaf);
if (graph.get(nei).size() == 1) leaves.add(nei);
}
}
return new ArrayList<>(leaves);
}
public static void main(String[] args) {
var a = new HashSet<>(findMinHeightTrees(4, new int[][] {{1, 0}, {1, 2}, {1, 3}}));
if (!a.equals(Set.of(1))) throw new AssertionError(a);
var b = new HashSet<>(findMinHeightTrees(6, new int[][] {{3, 0}, {3, 1}, {3, 2}, {3, 4}, {5, 4}}));
if (!b.equals(Set.of(3, 4))) throw new AssertionError(b);
System.out.println("ok");
}
}Edge cases
- Official samples: n = 4 with edges [[1,0],[1,2],[1,3]] returns [1]; n = 6 with [[3,0],[3,1],[3,2],[3,4],[5,4]] returns [3,4].
- A single node returns [0]. A single edge returns both endpoints.
Follow-ups
- If the graph were not a tree, you would first have to talk about connectedness and cycles; this problem promises a tree.
Interview script
"The best roots are the centroids. I peel the leaves of the tree layer by layer until one or two nodes are left, which is linear and avoids an O(n) BFS from every node."
Source: LeetCode 310: Minimum Height Trees
Weighted graphs
Sources (1)
- LeetCode 310: Minimum Height Treesleetcode.com