Skip to main content
Back to problems
#310
Medium Algorithms

Minimum height trees

Depth-First Search Breadth-First Search Graph Theory Topological Sort
42.4% acceptance
Jan 12, 2026
8885
416
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] = [ai, bi] indicates that there is an undirected edge between the two nodes ai and bi 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.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn find_min_height_trees(n: i32, edges: Vec<Vec<i32>>) -> Vec<i32> {
    if n == 1 {
      return vec![0];
    }
    
    let n = n as usize;
    let mut graph = vec![std::collections::HashSet::new(); n];
    
    for edge in edges {
      let u = edge[0] as usize;
      let v = edge[1] as usize;
      graph[u].insert(v);
      graph[v].insert(u);
    }
    
    let mut leaves: Vec<usize> = (0..n)
      .filter(|&i| graph[i].len() == 1)
      .collect();
    
    let mut remaining = n;
    
    while remaining > 2 {
      remaining -= leaves.len();
      let mut new_leaves = Vec::new();
      
      for leaf in leaves {
        let neighbor = *graph[leaf].iter().next().unwrap();
        graph[neighbor].remove(&leaf);
        if graph[neighbor].len() == 1 {
          new_leaves.push(neighbor);
        }
      }
      
      leaves = new_leaves;
    }
    
    leaves.into_iter().map(|x| x as i32).collect()
  }
}