Minimum Height Trees
2015-11-29 20:02
369 查看
题目:
https://leetcode.com/problems/minimum-height-trees/
思路:
所求结点为最长路径上的中间结点, 每次删除所有的叶子结点,多次删除后,最后剩下的就是中间结点
注:和求无向图的最长路径相似,还有另外一种解法
https://leetcode.com/problems/minimum-height-trees/
思路:
所求结点为最长路径上的中间结点, 每次删除所有的叶子结点,多次删除后,最后剩下的就是中间结点
注:和求无向图的最长路径相似,还有另外一种解法
class Solution { public: vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) { vector<int> *matrix=new vector<int> ; // 邻接表 int *degree=new int ; memset(degree,0,sizeof(int)*n); for(unsigned int i=0;i<edges.size();++i){// 构建邻接表 int x=edges[i].first; int y=edges[i].second; matrix[x].push_back(y); matrix[y].push_back(x); degree[x]++;// 记录每个结点的度 degree[y]++; } vector<int> leaf; for(int i=0;i<n;++i){//将叶子结点保存 if(degree[i]<=1){ leaf.push_back(i); } } int leafCutCount=0; while(leafCutCount<n-2){// 多轮删除叶子结点 & 根结点可能有一个或两个 vector<int> tem; for(unsigned int i=0;i<leaf.size();++i){ int leafNo=leaf[i]; degree[leafNo]--;//删除叶子 leafCutCount++; for(unsigned int j=0;j<matrix[leafNo].size();++j){ degree[matrix[leafNo][j]]--; if(degree[ matrix[leafNo][j] ]==1){// 保存新叶子 tem.push_back(matrix[leafNo][j]); } } } leaf=tem; } delete[] matrix; delete[] degree; return leaf; } };
相关文章推荐
- Spark大师之路:使用maven编译Spark
- 关于内存对齐的感悟
- MySQL之Event事件
- codeforces 381E Sereja and Brackets(线段树)
- Cloud Design Pattern - Static Content Hosting Pattern(静态内容托管)
- Form的Load事件如何添加
- Tower周报以及打印
- Trapping Rain Water
- 小美赛之matlab笔记
- 如何快速从Eclipse转向IDEA
- 使用按钮
- 自定义适配器
- 全功能智能车之CCD ADC 触发DMA传输(第十四篇)
- 逆袭指数-——杭电校赛(dfs)
- 第八届中国R语言会议(上海会场)精彩演讲视频 《借助API快速搭建自然语言处理平台》
- 初入移动端jq+html5
- HDU 1839 Delay Constrained Maximum Capacity Path(二分+SPFA)
- 97 Interleaving String
- OpenCV笔记(二)
- iOS ——逐帧动画