leetcode - Minimum Height Trees

题目:

https://leetcode.com/problems/minimum-height-trees/


参考这里


class Node
{
public:
	int id;
	unordered_set next;
	Node(int a) :id(a){}
};

class Solution {
public:
	vector findMinHeightTrees(int n, vector>& edges) {
		if (n == 1)
			return vector(1, 0);
		map g;
		for (int i = 0; inext.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 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 res;
		for (auto p : g)
		{
			res.push_back(p.first);
		}
		return res;
	}
};


你可能感兴趣的:(leetcode)