Description:
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.
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.
Example:
Given n = 4, edges = [[1, 0], [1, 2], [1, 3]]
0
|
1
/ \
2 3
return [1]
Given n = 6, edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]
0 1 2
\ | /
3
|
4
|
5
return [3, 4]
思路:
根据题目要求,在给定的无向图中找到所有的最小高度树,并返回树的根节点。最初的基本思想,以任意一个点作为根节点,然后找到其最大深度,这个深度则是树的高度。对所有的点都进行这样的操作,找出每个点作为根节点的树的高度,相比较则可以找出最小高度和最小高度树,最后统计其数量。
另外,基于BFS算法,可以通过找出所有入度(或出度,由于本题是无向图,所以入度与出度的值一致)为1的点,逐步对这些点进行遍历删除,那么最后剩下的点则是最小高度树的根节点。
下面是使用了C++的实现方法:
class Solution {
public:
vector<int> findMinHeightTrees(int n, vector<pair<int, int> >& edges) {
vector<vector<int> > G(n);
//构造图,使得每个点存储其所相连的所有点
for(int i=0; i<edges.size(); i++){
G[edges[i].first].insert(edges[i].second);
G[edges[i].second].insert(edges[i].first);
}
//当只有一个节点时
vector<int> cur;
if(n==1){
cur.push_back(0);
return cur;
}
//存储入度出度都为1的点
for(int i=0; i<G.size(); i++){
if (G[i].size() == 1) {
cur.push_back(i);
}
}
//对图进行BFS操作
while(true){
vector<int> next_visit;
for (int i=0;i<cur.size();i++) {
int node = cur[i];
for (int j=0;j<G[node].size();j++) {
int neighbor = G[node][j];
vector<int>::iterator iter = find(G[neighbor].begin(),G[neighbor].end(),node);//利用迭代器存储G[neighbor]中值与node相同的元素
G[neighbor].erase(iter);
if (G[neighbor].size() == 1) next_visit.push_back(neighbor);
}
}
if (next_visit.empty()) return cur;
cur = next_visit;
}
}
};