###### 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

2015-12-28 06:26:31

#### LeetCode 310. Minimum Height Trees（最小高度树）

2016-04-21 06:51:54

#### 310 Minimum Height Trees(Medium)

2015-11-30 18:06:03

#### 310. Minimum Height Trees

2016-03-13 11:45:06

#### [leetcode] 310. Minimum Height Trees

2016-02-23 15:56:23

#### LeetCode 310. Minimum Height Trees

2016-11-03 20:25:05

#### 310. Minimum Height Trees LeetCode

2016-03-16 14:50:50

#### Leetcode 310. Minimum Height Trees

2017-02-19 12:43:15

#### leetcode 310. Minimum Height Trees

2016-04-18 22:12:14

#### [LeetCode]310. Minimum Height Trees

2017-03-03 15:33:48

## 不良信息举报

LeetCode 310. Minimum Height Trees（超时）