forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 14
/
minimum-height-trees.cpp
50 lines (45 loc) · 1.43 KB
/
minimum-height-trees.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// Time: O(n)
// Space: O(n)
class Solution {
public:
vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) {
if (n == 1) {
return {0};
}
unordered_map<int, unordered_set<int>> neighbors;
for (const auto& e : edges) {
int u, v;
tie(u, v) = e;
neighbors[u].emplace(v);
neighbors[v].emplace(u);
}
vector<int> pre_level, cur_level;
unordered_set<int> unvisited;
for (int i = 0; i < n; ++i) {
if (neighbors[i].size() == 1) { // A leaf.
pre_level.emplace_back(i);
}
unvisited.emplace(i);
}
// A graph can have 2 MHTs at most.
// BFS from the leaves until the number
// of the unvisited nodes is less than 3.
while (unvisited.size() > 2) {
cur_level.clear();
for (const auto& u : pre_level) {
unvisited.erase(u);
for (const auto& v : neighbors[u]) {
if (unvisited.count(v)) {
neighbors[v].erase(u);
if (neighbors[v].size() == 1) {
cur_level.emplace_back(v);
}
}
}
}
swap(pre_level, cur_level);
}
vector<int> res(unvisited.begin(), unvisited.end());
return res;
}
};