leetcode_c++:图:Minimum Height Trees(310)
2016-08-28 15:14
435 查看
class Solution { public: vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) { //corner case if ( n <= 1 ) return {0}; //construct a edges search data stucture vector<unordered_set<int>> graph(n); for (auto e : edges) { graph[e.first].insert(e.second); graph[e.second].insert(e.first); } //find all of leaf nodes vector<int> current; for (int i=0; i<graph.size(); i++){ if (graph[i].size() == 1) current.push_back(i); } // BFS the graph while (true) { vector<int> next; for (int node : current) { for (int neighbor : graph[node]) { graph[neighbor].erase(node); if (graph[neighbor].size() == 1) next.push_back(neighbor); } } if (next.empty()) break; current = next; } return current; } };
相关文章推荐
- C/C++ 学习笔记:类相关
- C++STL的next_permutation
- leetcode_c++:图:Course Schedule II (207)
- leetcode_c++:图:Course Schedule(207)
- leetcode_c++:图:Clone Graph(133)
- C++数组初始化方法
- c++小数位 表示
- [C/C++笔面试]自己编程实现strcmp
- 迅雷2014C++研发笔试卷C解题分析
- C++智能指针详解(真的很经典 )
- Visual Stdio C++ 编译器 编译 (GSL) GNU Scientific Library 的方法介绍(6)
- Visual Stdio C++ 编译器 编译 (GSL) GNU Scientific Library 的方法介绍(6)
- C++标准库之mutex
- 简单工厂 c++
- 求给定数等于最少的几个完全平方数之和
- Introduction to C++ Programming in UE4——UE4官方文档翻译与理解(二)
- c语言遍历某文件夹下的所有文件 包括子文件夹
- Canny边缘检测及C++实现
- 一天一天算日期~
- 把脉vc++ 笔记