-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinimumHeightTrees.java
More file actions
54 lines (43 loc) · 1.33 KB
/
MinimumHeightTrees.java
File metadata and controls
54 lines (43 loc) · 1.33 KB
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
51
52
53
54
package graph;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class MinimumHeightTrees {
public static List<Integer> findMinHeightTrees(int n, int[][] edges) {
List<Integer> result = new ArrayList<>();
if (n == 1) {
result.add(0);
return result;
}
List<List<Integer>> adjList = new ArrayList<>();
int[] degree = new int[n];
for (int i = 0; i < n; i++) {
adjList.add(new ArrayList<>());
}
for (int[] edge : edges) {
adjList.get(edge[0]).add(edge[1]);
adjList.get(edge[1]).add(edge[0]);
degree[edge[0]]++;
degree[edge[1]]++;
}
Queue<Integer> leaves = new LinkedList<>();
for (int i = 0; i < n; i++) {
if (degree[i] == 1) leaves.offer(i);
}
while (n > 2) {
int size = leaves.size();
n -= size;
for (int i = 0; i < size; i++) {
int leaf = leaves.poll();
for (int neighbor : adjList.get(leaf)) {
if (--degree[neighbor] == 1) {
leaves.offer(neighbor);
}
}
}
}
result.addAll(leaves);
return result;
}
}