forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMinimumHeightTrees.java
64 lines (45 loc) · 1.13 KB
/
MinimumHeightTrees.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
class Solution {
public List<Integer> findMinHeightTrees(int n, int[][] edges) {
// find the level using BFS search
List<Integer> res = new ArrayList<>();
if (n <= 0) return res;
if (n == 1) {
res.add(0);
return res;
}
Map<Integer, Set<Integer>> map = new HashMap<>();
int[] degree = new int[n];
for(int[] edge: edges){
degree[edge[0]]++;
degree[edge[1]]++;
map.putIfAbsent(edge[0], new HashSet<>());
map.get(edge[0]).add(edge[1]);
map.putIfAbsent(edge[1], new HashSet<>());
map.get(edge[1]).add(edge[0]);
}
Queue<Integer> leaves = new LinkedList<>();
for(int i=0;i<n;i++){
//System.out.println("Indegree is "+ indegree[i] + " i is "+ i);
if(degree[i] == 1){
// add in queue
leaves.offer(i);
}
}
int count = n;
while(count>2){
int size = leaves.size();
count = count-size;
while(size-->0){
Integer leaf = leaves.poll();
for(Integer connection : map.get(leaf)){
degree[connection]--;
// map.get(connection).remove(leaf);
if(degree[connection] == 1){
leaves.offer(connection);
}
}
}
}
return new ArrayList<>(leaves);
}
}