Minimum Height Trees

Medium Topological sort

Problem

You are given an undirected tree of n nodes labeled 0 to n-1. The height of a tree is the number of edges on the longest downward path from a chosen root. Return every root that produces a minimum-height tree.

Original: LeetCode 310: Minimum Height Trees.

Examples

Example 1

Input`n = 4, edges = [[1, 0], [1, 2], [1, 3]]`
Output`[1]`

Example 2

Input`n = 6, edges = [[3, 0], [3, 1], [3, 2], [3, 4], [5, 4]]`
Output`[3, 4]`

Roots can be returned in any order.

Constraints

  • 1 <= n <= 2 * 10^4
  • edges.length == n - 1
  • 0 <= ai, bi < n
  • ai != bi
  • All the pairs (ai, bi) are distinct.
  • The given input is guaranteed to be a tree and there will be no repeated edges.

Hints

Solution

Tried it yourself? The approach, complexity, and code stay hidden until you choose.

Sources (1)
  1. LeetCode 310: Minimum Height Treesleetcode.com