Minimum Height Trees
Problem Statement
You are given a tree with n nodes labelled 0 to n − 1, and its n − 1 undirected edges. Any node can be the root. The height of the tree rooted at a node is the number of edges on the longest path from that root down to a leaf.
Return the labels of every root that gives the smallest height. These roots are the minimum height trees (MHTs). You can return them in any order.
n, the number of nodes, and edges, a list of n − 1 undirected pairs [a, b].
A list with the labels of all roots that give the minimum height.
Rooted at 1, the height is 1: every other node is one step away. Rooted at any leaf, the height is 2.
Rooted at 3 or at 4, the height is 2. Every other root gives a height of 3 or more, for example root 0 reaches 5 through 3 and 4.
- • 1 ≤ n ≤ 2 × 10^4
- • edges.length == n − 1
- • 0 ≤ a, b < n
- • a ≠ b
- • All the pairs (a, b) are distinct.
- • The input is a tree (connected, no cycles, no repeated edges).
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
BFS from each node to find its height, then keep the smallest
Remove all current leaves in rounds until at most 2 nodes are left; those are the answer
For each node r, run a BFS from r. The largest distance it finds is the height of the tree rooted at r. Keep every r with the smallest height. A tree has one or two such roots.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Topological Sort translate into production architectures and low-level memory mechanics.