您的位置:首页 > 其它

[LeetCode]Minimum Height Trees

2015-12-05 22:37 281 查看
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 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]


BFS 从度数为1的叶节点开始BFS扩展,记录每层的点数,最后找到的点(2个或者1个和n的奇偶有关)就是最小树的高度点了。


自己定义了节点数据,注意图的构建。

class Solution {
struct  vertice{
int index;
unordered_set<int> adj;
};
public:
vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) {
vector<int> ret;
if(edges.size()==0){
ret.push_back(0);
return ret; //1个节点的特殊情况
}
vector<vertice> Vertices;
for(int i=0; i<n; ++i){
vertice a;
a.index = i;
Vertices.push_back(a);
}

for(auto i=edges.begin(); i!=edges.end(); ++i){
Vertices[i->first].adj.insert(i->second);
Vertices[i->second].adj.insert(i->first); //记录图的数据
}

vector<vertice> leavel;
for(int i=0; i<n; ++i){
if(Vertices[i].adj.size()==1)
leavel.push_back(Vertices[i]);//第一层节点
}

while(n>2){
n -= leavel.size();
vector<vertice> temp;
for(int i=0; i<leavel.size(); ++i){
int root = *(leavel[i].adj.begin()); //找到根节点
Vertices[root].adj.erase(leavel[i].index);//去除子节点
if(Vertices[root].adj.size()==1) //如果度数为1,记录新的一层
temp.push_back(Vertices[root]);
}
leavel = temp;
}

for(int i=0; i<leavel.size(); ++i ){
ret.push_back(leavel[i].index); //结果输出
}
return ret;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: