Problem 535748 · medium · Level 05 Advanced Algorithms & Graphs

Centres of a Tree

topological sort · trees · leaf peeling

An undirected tree has n nodes 0 .. n-1 and n - 1 edges given as edges. Choosing any node as the root gives a rooted tree of some height (longest root-to-leaf edge count). Return a list of all nodes whose rooted height is minimal. The result always has one or two nodes and may be returned in any order.

Examples

Input:  n = 6, edges = [[0, 1], [1, 2], [1, 3], [3, 4], [2, 5]]
Output: [1]
Explanation: rooting at 1 gives height 2; every other root gives at least 3.

Input:  n = 5, edges = [[0, 2], [1, 2], [2, 3], [3, 4]]
Output: [2, 3]
Explanation: rooting at 2 or at 3 gives height 2; every other root gives 3.

Constraints

  • 1 <= n <= 2 * 10**4, the edges form a valid tree
  • Target: O(n) time.

Goals

  • Peel leaves layer by layer until at most two nodes remain
  • Explain why the surviving nodes minimise the tree's rooted height
Starting Python…