class TNode {
public:
int val;
unordered_set<TNode*> neigh;
TNode(int val) {
this->val = val;
}
};
class Solution {
public:
vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) {
map<int, TNode*> val_node;
for(int i = 0; i < n; i++) {
TNode* tmp = new TNode(i);
val_node[i] = tmp;
}
for(int i = 0; i < edges.size(); i++) {
pair<int, int> pp = edges[i];
val_node[pp.first]->neigh.insert(val_node[pp.second]);
val_node[pp.second]->neigh.insert(val_node[pp.first]);
}
map<int, TNode*>::iterator m_iter;
while(val_node.size() > 2) {
list<TNode*> listg;
for(m_iter = val_node.begin(); m_iter != val_node.end(); m_iter++) {
if(m_iter->second->neigh.size() == 1) {
listg.push_back(m_iter->second);
}
}
list<TNode*>::iterator l_iter;
for(l_iter = listg.begin(); l_iter != listg.end(); l_iter++) {
TNode* p = (*(*l_iter)->neigh.begin());
p->neigh.erase(*l_iter);
(*l_iter)->neigh.erase(p);
val_node.erase((*l_iter)->val);
}
}
vector<int> res;
for(m_iter = val_node.begin(); m_iter != val_node.end(); m_iter++) {
res.push_back(m_iter->first);
}
return res;
}
};