A tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.

Given a tree of n nodes labelled from 0 to n - 1, and an array of n - 1 edges where edges[i] = [aᵢ, bᵢ] indicates that there is an undirected edge between the two nodes aᵢ and bᵢ in the tree, you can choose any node of the tree as the root.

When you select a node x as the root, the result tree has height h. Among all possible rooted trees, those with minimum height (i.e. min(h)) are called minimum height trees (MHTs).

Return a list of all MHTs' root labels. You can return the answer in any order.

The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.

Input & Output

Example 1 — Basic Tree
$ Input: n = 4, edges = [[1,0],[1,2],[1,3]]
Output: [1]
💡 Note: Node 1 is connected to all other nodes. When 1 is root, max path length is 1 (1→0, 1→2, or 1→3). Any other root gives height 2.
Example 2 — Linear Tree
$ Input: n = 6, edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]
Output: [3,4]
💡 Note: Both nodes 3 and 4 are centers. Root 3 gives max path 3→4→5 (length 2). Root 4 gives max path 0→3→4 or 1→3→4 (length 2).
Example 3 — Single Node
$ Input: n = 1, edges = []
Output: [0]
💡 Note: Only one node exists, so it must be the root with height 0.

Constraints

  • 1 ≤ n ≤ 2 × 104
  • edges.length == n - 1
  • 0 ≤ aᵢ, bᵢ < n
  • aᵢ ≠ bᵢ
  • All the pairs (aᵢ, bᵢ) are distinct
  • The given input is guaranteed to be a tree and there will be no repeated edges

Visualization

Tap to expand
Minimum Height Trees: Find the Best RootOriginal TreeRoot at Node 0 (Height = 2)Root at Node 1 (Height = 1)01230 (root)1 (root)Center nodes minimize the maximum distance to any leafAnswer: Node 1 gives minimum height tree
Understanding the Visualization
1
Input Tree
Undirected tree with nodes 0 to n-1
2
Try Different Roots
Each root choice gives different height
3
Find Minimum
Center nodes give minimum height
Key Takeaway
🎯 Key Insight: The center nodes of a tree (at most 2) always produce minimum height trees
Asked in
Google 45 Amazon 38 Facebook 32 Microsoft 28
95.0K Views
Medium Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen