# Roots of a tree which give minimum height

Given an undirected graph, which has tree characteristics. It is possible to choose any node as root, the task is to find those nodes only which minimize the height of tree.

Example:
In below diagram all node are made as root one by one, we can see that when 3 and 4 are root, height of tree is minimum(2) so {3, 4} is our answer.

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

We can solve this problem by first thinking about 1-D solution, that is if a longest graph is given, then the node which will minimize the height will be mid node if total node count is odd or mid two node if total node count is even. This solution can be reached by following approach – Start two pointers from both end of the path and move one step each time, until pointers meet or one step away, at the end pointers will be at those nodes which will minimize the height because we have divided the nodes evenly so height will be minimum.
Same approach can be applied to a general tree also. Start pointers from all leaf nodes and move one step inside each time, keep combining pointers which overlap while moving, at the end only one pointer will remain on some vertex or two pointers will remain at one distance away. Those node represent the root of the vertex which will minimize the height of the tree.
So we can have only one root or at max two root for minimum height depending on tree structure as explained above. For implementation we will not use actual pointers instead we’ll follow BFS like approach, In starting all leaf node are pushed into the queue, then they are removed from tree, next new leaf node are pushed in queue, this procedure keeps on going until we have only 1 or 2 node in our tree, which represent the result.
As we are accessing each node once, total time complexity of solution is O(n).

## Python

Output:

3 4

This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

My Personal Notes arrow_drop_up

Article Tags :
Practice Tags :

7

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.