Skip to content

Commit f610425

Browse files
committed
[feat ]: leetcode 310
Signed-off-by: Bo-Wei Chen(BWbwchen) <tim.chenbw@gmail.com>
1 parent abc6f9c commit f610425

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
class Solution {
2+
public:
3+
vector<int> findMinHeightTrees(int n, vector<vector<int>>& edges) {
4+
// Since there are at most 2 nodes as the centre(A tree node will have at most 2 neighbor, If 3 centre, the middle one will become new centre).
5+
// How to find the centre?
6+
// remove the leaf node layer by layer, the remain 1 or 2 nodes are the centre.
7+
// How to detect a node is a leaf node or not?
8+
// keep tracking the edge of each node!
9+
if (n == 1)
10+
return {0};
11+
12+
vector<int> in_degree(n, 0);
13+
vector<vector<int>> graph(n);
14+
for (auto e : edges) {
15+
in_degree[e[0]]++;
16+
in_degree[e[1]]++;
17+
graph[e[0]].push_back(e[1]);
18+
graph[e[1]].push_back(e[0]);
19+
}
20+
21+
queue<int> q;
22+
for (int node = 0; node < in_degree.size(); ++node) {
23+
if (in_degree[node] == 1) // leaf node
24+
q.push(node);
25+
}
26+
27+
int leaf_node = 0;
28+
while(n - leaf_node > 2) { // at most 2 centres
29+
// remove leaf node
30+
int tmp_leaf_node = q.size();
31+
leaf_node += tmp_leaf_node;
32+
for (int i = 0; i < tmp_leaf_node; ++i) {
33+
int leaf = q.front();
34+
q.pop();
35+
36+
for (auto neighbor : graph[leaf]) {
37+
if (--in_degree[neighbor] == 1)
38+
q.push(neighbor);
39+
}
40+
}
41+
}
42+
43+
vector<int> ret;
44+
while(!q.empty()) {
45+
ret.push_back(q.front());
46+
q.pop();
47+
}
48+
return ret;
49+
}
50+
};

0 commit comments

Comments
 (0)