关闭

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

161人阅读 评论(0) 收藏 举报
分类:
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;
    }

};
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:102742次
    • 积分:6687
    • 等级:
    • 排名:第3497名
    • 原创:589篇
    • 转载:2篇
    • 译文:0篇
    • 评论:2条
    最新评论