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 are 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.node
Format
The graph contains n
nodes which are labeled from 0
to n - 1
. You will be given the number n
and a list of undirected edges
(each edge is a pair of labels).數組
You can assume that no duplicate edges will appear in edges
. Since all edges are undirected, [0, 1]
is the same as [1, 0]
and thus will not appear together in edges
.app
Example 1:spa
Given n = 4
, edges = [[1, 0], [1, 2], [1, 3]]
code
0 | 1 / \ 2 3
return [1]
orm
Example 2:blog
Given n = 6
, edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]
隊列
0 1 2 \ | / 3 | 4 | 5
return [3, 4]
get
Solution:it
使用二維數組構造圖G[N][N],數組G[i]表示節點i的全部相鄰節點。數組dist[i]記錄節點i的度。
一、根據輸入構造圖G和數組dist
二、把度位1的節點放入BFS隊列Q
三、刪除全部度爲1的節點,並更新和這些節點相鄰的節點的度。當度爲1時繼續加入隊列Q。
四、重複3, 直到剩餘節點數<=2
1 vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) 2 { 3 if (n == 1) 4 return {0}; 5 vector<int> result; 6 vector<int> dist(n, 0); 7 vector<vector<int> > G(n, vector<int>()); 8 queue<int> Q; 9 10 // init graph 11 for (auto elem : edges) 12 { 13 G[elem.first].push_back(elem.second); 14 G[elem.second].push_back(elem.first); 15 dist[elem.second]++; 16 dist[elem.first]++; 17 } 18 for (int node = 0; node < dist.size(); node++) 19 { 20 if (dist[node] == 1) 21 Q.push(node); 22 } 23 24 int count = n; 25 while (count > 2) 26 { 27 int qsize = Q.size(); 28 for (int i = 0; i < qsize; i++) 29 { 30 int node = Q.front(); 31 Q.pop(); 32 count--; 33 for (auto elem : G[node]) 34 { 35 dist[elem]--; 36 if (dist[elem] == 1) 37 Q.push(elem); 38 } 39 } 40 } 41 42 while (!Q.empty()) 43 { 44 result.push_back(Q.front()); 45 Q.pop(); 46 } 47 48 return result; 49 }