Minimum Height Trees

来源:互联网 发布:gdi 矩阵变换 编辑:程序博客网 时间:2024/06/05 03:18

c++

class Solution {public:    vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) {        if (n == 1) return vector<int>(1,0);        unordered_map<int, unordered_set<int>> graph;        for (auto &v : edges) {            graph[v.first].insert(v.second);            graph[v.second].insert(v.first);        }        vector<int> leaves;        for (auto &v : graph) {            if (v.second.size() == 1)                leaves.push_back(v.first);        }        while (n>2){            n -= leaves.size();            vector<int> new_leaves;            for (auto &v : leaves) {                int tmp = *(graph[v].begin());                graph[tmp].erase(v);                if (graph[tmp].size() == 1)                    new_leaves.push_back(tmp);            }            leaves = new_leaves;        }        return leaves;    }};

https://leetcode.com/discuss/71763/share-some-thoughts

0 0
原创粉丝点击