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.
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).
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 firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Applications of Minimum Spanning Tree Problem
- Boruvka's algorithm for Minimum Spanning Tree
- Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
- Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
- Find minimum s-t cut in a flow network
- Find the minimum cost to reach destination using a train
- Karger's algorithm for Minimum Cut | Set 1 (Introduction and Implementation)
- Karger’s algorithm for Minimum Cut | Set 2 (Analysis and Applications)
- Steiner Tree Problem
- Minimum steps to reach a destination
- Minimum time required to rot all oranges
- Check whether given degrees of vertices represent a Graph or Tree
- Kruskal's Minimum Spanning Tree using STL in C++
- Check if two nodes are on same path in a tree
- Finding minimum vertex cover size of a graph using binary search