[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
edge is a pair of labels).
You can assume that no duplicate edges will appear in
Example 1:
Given
return
Example 2:
Given
return
to find all the MHTs and return a list of their root labels.
Format
The graph contains
nnodes which are labeled from
0to
n - 1. You will be given the number
nand 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; } };
相关文章推荐
- centos下编译glib Library并安装
- JavaScript跨域
- 轻松学习JavaScript十一:JavaScript基本类型(包含类型转换)和引用类型
- 用相对定位进行布局。
- c++中多参数
- 八大排序算法分析-插入排序
- 图的存储结构
- hdoj the Sum of Cube 5053 (简单数学)
- [译]Android音频: 如何使用AudioTrack播放一个WAV格式文件?
- 去除搜狐广告
- Swift工程下使用OC版本的MKNetworkKit
- CTP训练营之牛刀小试
- 启动一个倒计时器
- C语言程序设计整理(1)
- C语言之结构体
- java学习心得
- W3C代码标准规范
- 10017---jQuery--尺寸
- 每天一点统计学——————————————序
- PS替换图标颜色