Graphs Topological sort
461. Minimum Height Trees
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
Input: n = 9
edges = [[0, 3],
[3, 8],
[3, 6],
[6, 1],
[6, 5],
[5, 2],
[0, 7],
[6, 4]]
[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
Input: n = 1, edges = []
[0]Explanation: The only vertex is the only possible root. Its tree has height 0.
Example 3
Input: n = 2, edges = [[1, 0]]
[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.
Constraints
1 ≤ n ≤ 105edges.length == n - 1edges[i].length == 20 ≤ ui, vi < nui ≠ 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.