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 = 4, edges = [[1, 0], [1, 2], [1, 3]]
Output: [1]

Input:  n = 6, edges = [[3, 0], [3, 1], [3, 2], [3, 4], [5, 4]]
Output: [3, 4]
Explanation: rooting at 3 or at 4 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…