# LeetCode 310. Minimum Height Trees（超时）

For a undirected graph with tree characteristics, we can choose any node as the root. The result graph is then a rooted tree. Among all possible rooted trees, those with minimum height are called minimum height trees (MHTs). Given such a graph, write a function to find all the MHTs and return a list of their root labels.

Format
The graph contains n nodes which are labeled from 0 to n - 1. You will be given the number n and a list of undirected edges (each edge is a pair of labels).

You can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges.

Example 1:

Given n = 4edges = [[1, 0], [1, 2], [1, 3]]

        0
|
1
/ \
2   3


return [1]

Example 2:

Given n = 6edges = [[0, 3], [1, 3], [2, 3], [4, 3], [5, 4]]

     0  1  2
\ | /
3
|
4
|
5


return [3, 4]

Hint:

1. How many MHTs can a graph have at most?

class Solution {
public:
vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) {
vector<int> re;
if (n == 1)
{
re.push_back(0);
return re;
}
map<int, vector<int>> list;
for (int i = 0; i<n - 1; i++)
{
list[edges[i].first].push_back(edges[i].second);
list[edges[i].second].push_back(edges[i].first);
}
map<int, vector<int>> list1;
while (1)
{
list1 = list;
if (list.size() == 1)
{
map<int, vector<int>>::iterator j = list.begin();
re.push_back(j->first);
break;
}
if (list.size() == 2)
{
map<int, vector<int>>::iterator j = list.begin();
re.push_back(j->first);
j++;
re.push_back(j->first);
break;
}
for (map<int, vector<int>>::iterator i = list1.begin(); i != list1.end(); i++)
{
if (list1[i->first].size() == 1)
{
int tmp = list1[i->first][0];
list[tmp].erase(find(list[tmp].begin(), list[tmp].end(), i->first));
list.erase(i->first);
}
}
}
return re;
}
};

• 本文已收录于以下专栏：

举报原因： 您举报文章：LeetCode 310. Minimum Height Trees（超时） 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)