-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path310. Minimum Height Trees.java
37 lines (37 loc) · 1.07 KB
/
310. Minimum Height Trees.java
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
class Solution {
public List<Integer> findMinHeightTrees(int n, int[][] edges) {
if (n == 1) {
return Collections.singletonList(0);
}
List<Integer>[] g = new List[n];
Arrays.setAll(g, k -> new ArrayList<>());
int[] degree = new int[n];
for (int[] e : edges) {
int a = e[0], b = e[1];
g[a].add(b);
g[b].add(a);
++degree[a];
++degree[b];
}
Queue<Integer> q = new LinkedList<>();
for (int i = 0; i < n; ++i) {
if (degree[i] == 1) {
q.offer(i);
}
}
List<Integer> ans = new ArrayList<>();
while (!q.isEmpty()) {
ans.clear();
for (int i = q.size(); i > 0; --i) {
int a = q.poll();
ans.add(a);
for (int b : g[a]) {
if (--degree[b] == 1) {
q.offer(b);
}
}
}
}
return ans;
}
}