Problem 633
Minimum Height Trees
Medium · 20 pts · Graph, Tree, Breadth-First Search, Topological Sort
Problem
A tree with N nodes (numbered from 1) can be rooted at any node, and the height of the rooted tree is the number of edges on the longest path from the root down to a leaf. Find all roots that give the minimum height, and print them in increasing order. There are always one or two such roots: the centre of the tree. Repeatedly remove all current leaves layer by layer; the one or two nodes that remain last are the answer.
Input
The first line contains N and M = N - 1. Each of the next N - 1 lines contains an edge u v of the tree.
Output
Print the roots of minimum height trees in increasing order, separated by spaces.
Constraints
1 <= N <= 20000; the edges form a tree
Example input
5 4 1 4 2 4 3 4 5 4
Example output
4
Explanation
In the tree with edges 1-4, 2-4, 3-4 and 5-4, rooting at 4 gives height 1, while any other root gives height 2. So the only answer is 4.