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 - BFS Approach INPUT Tree Graph (n=4) 0 1 2 3 n = 4 edges = [[1,0],[1,2],[1,3]] Node 1 connects to all others ALGORITHM STEPS 1 Find Leaf Nodes Nodes with degree 1: [0,2,3] 2 BFS from Leaves Remove leaves layer by layer 3 Trim Towards Center Continue until 1-2 nodes left 4 Return Centroids Remaining nodes are MHT roots BFS Trimming Process Round 1: 0 2 3 removed Remaining: 1 -- MHT root! Only 1 node left = Answer FINAL RESULT Tree rooted at node 1 1 root 0 2 3 Height = 1 (minimum!) Output: [1] OK - Verified! Node 1 is the only MHT root (height=1) Key Insight: The MHT roots are always the centroids of the tree. By repeatedly removing leaf nodes (BFS from outside), we converge to 1 or 2 central nodes. These centroids minimize the maximum distance to any other node, resulting in minimum tree height. Time Complexity: O(n) | Space Complexity: O(n) TutorialsPoint - Minimum Height Trees | BFS Leaf Trimming Approach
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