The first line of the input contains an integer, 'T,β denoting the number of test cases.
The first line of each test case contains an integer, 'N,β denoting the number of nodes.
The next βNβ-1 lines of each test case contain two space-separated integers, βXβ and βYβ separated by a single space, βXβ and βYβ denote the two nodes connected by an undirected edge.
For each test case, return the list of all such nodes such that rooting the tree on that node gives the minimum height possible.
Return all the nodes in a sorted manner.
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 10^5
1 <= X,Y <= N
The input edges form a tree.
Time limit: 1 sec
The idea is to iterate through all the nodes one by one, select that node as the root of the tree and find the height of the formed tree. We will also maintain a list of nodes that gives the minimum height. Whenever we find a node that gives a minimum height, we will clear our list and that node to the list and update the minimum height that we have found till now. If a node gives the same height as the minimum height, then we will add that node to our output list. Note that we will ignore all nodes that give greater height than minimum height. To find the height of a rooted tree we can use Depth First Search (DFS) or Breadth First Search (BFS).
Steps:
The idea is to observe the fact that all such nodes that give the minimum height when the tree is rooted on it lie on a single path, which is the longest simple path in the tree. It can be seen that for a simple path representing a line tree, it is always optimal to root the tree at the middle of the path to get the minimum height. Similarly, for any tree it is always optimal to root the tree at the middle of the longest path to get minimum height. If the length of the longest path is even, then there will be a single optimal node which will be present in the middle of the path. Otherwise, the two nodes that lie in the middle of the longest path can be used as the root. Therefore, the number of optimal roots are always lesser than or equal to 2.
To find the optimal nodes, we will use an approach similar to Breadth First Search. Initially, we will enqueue all the leaves of the tree into the queue and then in every iteration, we will dequeue all the leaves from the queue and remove all the leaves from the tree, and enqueue all the newly formed leaves into the queue. We will end our algorithm, when the number of elements remaining in the tree are no more than 2. This idea works because the nodes that lie on the middle of the longest path will always be the last nodes to be removed from the queue. Note that, we can simulate the removal of leaf nodes of the tree by keeping track of the degrees of each node.
Steps: