-
Notifications
You must be signed in to change notification settings - Fork 0
/
310.最小高度树.java
58 lines (54 loc) · 1.63 KB
/
310.最小高度树.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
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
/*
* @lc app=leetcode.cn id=310 lang=java
*
* [310] 最小高度树
*/
// @lc code=start
class Solution {
public static List<Integer> findMinHeightTrees(int n, int[][] edges) {
int edge_length = edges.length;
if(edge_length==0) {
LinkedList<Integer> r = new LinkedList<Integer>();
r.add(0);
return r;
}
// int out[] = new int[n];
// int in[] = new int[n];
List<Integer> result = new LinkedList<Integer>();
LinkedList<Integer> tmp = new LinkedList<Integer>();
HashMap<Integer,List<Integer>> E = new HashMap<>();
for(int i=0;i<n;i++){
E.put(i, new LinkedList<Integer>());
}
// Arrays.fill(out, 0);
for(int i=0;i<edge_length;i++){
E.get(edges[i][0]).add(edges[i][1]);
E.get(edges[i][1]).add(edges[i][0]);
}
int total = n;
for(int i=0;i<n;i++){
if(E.get(i).size()==1){
tmp.add(i);
}
}
while(total>2){
total = total - tmp.size();
LinkedList<Integer> new_temp = new LinkedList<Integer>();
while(!tmp.isEmpty()) {
int i = tmp.pop();
if(E.get(i).size()==1){
int cur=E.get(i).remove(0);
E.get(cur).removeIf(s->s.intValue()==i);
if(E.get(cur).size()==1) new_temp.add(cur);
}
}
tmp = new_temp;
}
return tmp;
}
}
// @lc code=end