For a undirected graph with tree characteristics, we can choose any node as the root. The result graph is then a rooted tree. Among all possible rooted trees, those with minimum height is called minimum height trees (mhts). Given such a graph, write a function to find all the mhts and return a list of their root labels.
Format
The graph contains n nodes which is labeled from 0 to n - 1 . You'll be given the number and n a list of undirected edges (each edge is a pair of labels).
You can assume that no duplicate edges would appear in edges . Since all edges was undirected, is the same as and thus would not [0, 1] [1, 0] appear together in edges .
Example 1:
Given n = 4 ,edges = [[1, 0], [1, 2], [1, 3]]
0 | 1 / 2 3
Return[1]
Example 2:
Given n = 6 ,edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]
0 1 2 \ |/ 3 | 4 | 5
Return[3, 4]
Show Hint
Note:
(1) According to the definition of the tree on Wikipedia: "A tree was an undirected graph in which any and vertices is connect Ed by exactly one path. In the other words, any connected graph without simple cycles is a tree. "
(2) The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.
vector<int> Findminheighttrees (intN, vector<pair<int,int>>&edges) { //Corner Case if(N <=1)return{0}; //construct a edges search data stucturevector<unordered_set<int>>graph (n); for(Auto e:edges) {Graph[e.first].insert (E.second); Graph[e.second].insert (E.first); } //Find all of the leaf nodesvector<int>Current ; for(intI=0; I<graph.size (); i++){ if(graph[i].size () = =1) Current.push_back (i); } //BFS the graph while(true) {vector<int>Next; for(intnode:current) { for(intNeighbor:graph[node]) {graph[neighbor].erase (node); if(graph[neighbor].size () = =1) Next.push_back (neighbor); } } if(Next.empty ()) Break; Current=Next; } returnCurrent ;}
Remove the outermost circle of leaf nodes at a time. The last remaining set of nodes is what is asked.
310. Minimum Height Trees--Find out which nodes in the graph are rooted, and the depth of the tree is minimal