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