oneby7

Graphs Topological sort

461. Minimum Height Trees

Medium

You are given a tree with n vertices, numbered from 0 to n - 1. Each pair [u, v] in edges is an edge between vertices u and v. Every vertex can be reached from every other, and there is no cycle.

Any vertex can be picked as the root. The tree then hangs down from it, and its height is the number of edges on the longest path from the root down to a leaf. Put another way, the height is the distance from the root to the vertex farthest from it.

Return every vertex that gives the smallest possible height when picked as the root. You may return them in any order.

Example 1

012345678

Input: n = 9 edges = [[0, 3], [3, 8], [3, 6], [6, 1], [6, 5], [5, 2], [0, 7], [6, 4]]

Output: [3,6]

Explanation: With root 3, the farthest vertex is 2, three edges away along 3 → 6 → 5 → 2. With root 6, the farthest is 7, also three edges away. Every other root gives a height of 4 or more.

Example 2

0

Input: n = 1, edges = []

Output: [0]

Explanation: The only vertex is the only possible root. Its tree has height 0.

Example 3

01

Input: n = 2, edges = [[1, 0]]

Output: [0,1]

Explanation: Either vertex as the root gives a height of 1, so both are in the answer.

Check your understanding

Work out the answer for this input before you write any code.

n = 4, edges = [[0, 2], [2, 3], [3, 1]]

Constraints

  • 1 ≤ n ≤ 105
  • edges.length == n - 1
  • edges[i].length == 2
  • 0 ≤ ui, vi < n
  • ui ≠ vi
  • The edges form a tree. Every vertex can be reached from every other.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.