 All Problems
Minimum Height Trees
medium
graph
bfs
topological sort
google
amazon
facebook

A tree is an undirected graph with n nodes labeled 0 to n-1 where n >= 1. You are given n and a list of n-1 edges. Return a list of all MHT root labels. An MHT is a tree rooted such that the height is minimized.

Example 1:

Input:
4
3
1 0
1 2
1 3
Output: 1

Example 2:

Input:
6
5
3 0
3 1
3 2
3 4
5 4
Output: 3 4

Constraints:

  • 1 ≤ n ≤ 2 × 10⁴
  • edges.length == n - 1
  • No repeated edges, no self-loops

Input format: First line: n. Second line: number of edges. Then edges.

Output format: MHT root labels, space-separated.

Run to check your code against the sample cases, or submit to run every case