[LeetCode] Minimum Height Trees

310. Minimum Height Trees

A tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.

Given a tree of n nodes labelled from 0 to n - 1, and an array of n - 1 edges where edges[i] = [ai, bi] indicates that there is an undirected edge between the two nodes ai and bi in the tree, you can choose any node of the tree as the root. When you select a node x as the root, the result tree has height h. Among all possible rooted trees, those with minimum height (i.e. min(h)) are called minimum height trees (MHTs).

Return a list of all MHTs’ root labels. You can return the answer in any order.

The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.

  • new solution update 2022.03.17
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
class Solution {
public:
vector<int> findMinHeightTrees(int n, vector<vector<int>>& edges) {
if(n==1)return{0};
vector<int> degree(n,0);
vector<vector<int>> adj(n);
for(auto e : edges) {
adj[e[0]].push_back(e[1]);
adj[e[1]].push_back(e[0]);
degree[e[0]]++;
degree[e[1]]++;
}
queue<int> q;
vector<int> res;
for(int i = 0; i < n; i++) {
if(degree[i] == 1) {
q.push(i);
}
}
while(!q.empty()) {
res.clear();
int sz = q.size();
while(sz--) {
auto node = q.front(); q.pop();
res.push_back(node);
for(auto near : adj[node]) {
if(--degree[near] == 1) {
q.push(near);
}
}
}
}
return res;

}
};
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
class Solution {
int height = INT_MAX;
int getChildHeight(int from, int me, vector<list<pair<int, int>>>& g) {
int res = 0;
for(auto& child : g[me]) {
if(child.first != from) {
if(child.second == -1) {
res = max(res, child.second = getChildHeight(me, child.first, g));
} else {
res = max(res, child.second);
}
}
}
return res + 1;
}

int getHeight(int root, vector<list<pair<int, int>>>& g) {
int res = 0;
for(auto& child : g[root]) {
res = max(res, getChildHeight(root, child.first, g));
}
return res;
}
public:
vector<int> findMinHeightTrees(int n, vector<vector<int>>& edges) {
vector<int> res;
vector<list<pair<int, int>>> g(n, list<pair<int,int>>());
for(auto edge : edges) {
g[edge[0]].push_back({edge[1], -1});
g[edge[1]].push_back({edge[0], -1});
}

for(int i = 0; i < n; i++) {
int level = getHeight(i, g);
if(level == height) {
res.push_back(i);
} else if(level < height) {
height = level;
res.clear();
res.push_back(i);
}
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/03/27/PS/LeetCode/minimum-height-trees/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.