LandscapeMi

landscapemi的博客

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

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;
    }

};
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/mijian1207mijian/article/details/52345903
个人分类: leetcode(c++)
上一篇leetcode_c++:图:Course Schedule II (207)
下一篇leetcode_c++:图:Reconstruct Itinerary (332)
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭