leetcode_c++:图:Minimum Height Trees(310)

原创 2016年08月28日 15:14:25
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;
    }

};
版权声明:本文为博主原创文章,未经博主允许不得转载。

leetcode 310. Minimum Height Trees BFS,找无向连通图的直径

想要找到图里面的MHT,就要找出最长路径,最长路径的中点就是MHT的根,当最长路径的树节点个数是奇数的时候,MHT只有一棵,当最长路径的树节点个数是偶数的时候,MHT有两棵。找出无向连通图里面的直径,...

LeetCode 310 Minimum Height Trees

题目For a undirected graph with tree characteristics, we can choose any node as the root. The result g...

Leetcode: 310.Minimum Height Trees

Leetcode: 310.Minimum Height Trees

【LEETCODE】310-Minimum Height Trees

For a undirected graph with tree characteristics, we can choose any node as the root. The result gra...

[leetcode] 310.Minimum Height Trees

leetcode 310.Minimum Height Trees

leetcode 310. Minimum Height Trees

For a undirected graph with tree characteristics, we can choose any node as the root. The result gra...

leetcode 310. Minimum Height Trees 解题报告

原题链接原题链接解题思路常规方法可以使用BFS或者DFS,对每个点都遍历一遍,求出所有点组成的树的高度,然后找出哪些高度最小的节点,可以通过不断更新最低高度来进行剪枝。但是时间复杂度过高。 最终的解...
  • jly0612
  • jly0612
  • 2016年09月04日 17:08
  • 348

LeetCode-310. Minimum Height Trees (JAVA) 图中最矮的树

LeetCode-310. Minimum Height Trees (JAVA) 图中最矮的树

LeetCode 310. Minimum Height Trees

310. Minimum Height TreesFor a undirected graph with tree characteristics, we can choose any node as...

Leetcode 310. Minimum Height Trees【medium】

题目: For a undirected graph with tree characteristics, we can choose any node as the root. The res...
  • o555ddd
  • o555ddd
  • 2016年10月04日 11:16
  • 183
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:leetcode_c++:图:Minimum Height Trees(310)
举报原因:
原因补充:

(最多只允许输入30个字)