Given an undirected graph which has a tree characteristics represented using an adjacency list adj[][], we can choose any vertex as the root of the tree. Find all the vertices that, when chosen as the root, result in the minimum possible height of the tree.
Note: The height of a rooted tree is defined as the maximum number of edges on the path from the root to any leaf node.
[Naive Approach] By exploring all node as Root - O(V^2) Time and O(V) Space
The idea is to explore each node one by one as the root. For every node, we treat it as the root and find the height of the tree starting from that node to its farthest leaf node. After calculating heights for all nodes, we store the nodes with the minimum height in the result.
Output
2 3
[Expected Approach] Using Topological Sorting - O(V) Time and O(V) Space
If we take node 1 as root - height = 2 (minimum height)
If we take node 2 as root - height = 2 (minimum height)
If we take node 3 as root - height = 3
So, node 1 and 2 (which lies in the middle) gives the minimum height. Similarly, in longer or more complex trees, the center or middle nodes always produce the minimum height.
Why the Center Works ?
The reason is simple: in a tree, every node is connected by exactly one path. If we keep moving inward by removing outermost leaves, we are getting closer to the middle of the longest path.Once all the leaves are removed, the last one or two remaining nodes must be the centers of the tree. These are the roots that minimize the height β because they are equally distant from all edges of the tree.
The idea is we use a topological sortβlike approach. First, we identify all the leaf nodes(degree 1). We then remove these leaf nodes from the graph. As we remove each leaf, we decrease the degree of its connected neighbor nodes. After removal, if any of those neighbors become new leaves (their degree becomes 1), we mark them for the next round.We keep repeating this process level by level, trimming the tree from the outside in.
In the end, when only one or two nodes remain, those are the center nodes of the graph β the points that are equally close to all other nodes and give the minimum possible height when chosen as roots.