-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.java
More file actions
55 lines (42 loc) · 1.31 KB
/
Copy pathsolution.java
File metadata and controls
55 lines (42 loc) · 1.31 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
55
class Solution {
public ArrayList<Integer> minHeightRoot(int V, int[][] edges) {
ArrayList<Integer> result = new ArrayList<>();
if (V == 1) {
result.add(0);
return result;
}
List<List<Integer>> adj = new ArrayList<>();
for (int i = 0; i < V; i++)
adj.add(new ArrayList<>());
int[] degree = new int[V];
// Build graph
for (int[] e : edges) {
adj.get(e[0]).add(e[1]);
adj.get(e[1]).add(e[0]);
degree[e[0]]++;
degree[e[1]]++;
}
Queue<Integer> q = new LinkedList<>();
// Initial leaves
for (int i = 0; i < V; i++) {
if (degree[i] == 1)
q.offer(i);
}
int remainingNodes = V;
while (remainingNodes > 2) {
int size = q.size();
remainingNodes -= size;
while (size-- > 0) {
int leaf = q.poll();
for (int neighbor : adj.get(leaf)) {
degree[neighbor]--;
if (degree[neighbor] == 1) {
q.offer(neighbor);
}
}
}
}
result.addAll(q);
return result;
}
}