题目:
https://leetcode.com/problems/minimum-height-trees/
参考这里
class Node
{
public:
int id;
unordered_set<int> next;
Node(int a) :id(a){}
};
class Solution {
public:
vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) {
if (n == 1)
return vector<int>(1, 0);
map<int, Node*> g;
for (int i = 0; i<edges.size(); ++i)
{
if (g.count(edges[i].first) == 0)
{
Node* tmp = new Node(edges[i].first);
tmp->next.emplace(edges[i].second);
g[edges[i].first] = tmp;
}
else
{
g[edges[i].first]->next.emplace(edges[i].second);
}
if (g.count(edges[i].second) == 0)
{
Node* tmp = new Node(edges[i].second);
tmp->next.emplace(edges[i].first);
g[edges[i].second] = tmp;
}
else
{
g[edges[i].second]->next.emplace(edges[i].first);
}
}
vector<int> erase_keys;
while (g.size()>2)
{
for (auto p : g)
{
if ((p.second->next).size() == 1)
{
erase_keys.push_back(p.first);
}
}
for (int i = 0; i < erase_keys.size(); ++i)
{
for (auto id : g[erase_keys[i]]->next)
{
g[id]->next.erase(erase_keys[i]);
}
g.erase(erase_keys[i]);
}
erase_keys.clear();
}
vector<int> res;
for (auto p : g)
{
res.push_back(p.first);
}
return res;
}
};