Skip to content

Commit 6683631

Browse files
Sean PrashadSean Prashad
authored andcommitted
Add 310_Minimum_Height_Trees.java
1 parent ce854b9 commit 6683631

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
class Solution {
2+
public List<Integer> findMinHeightTrees(int n, int[][] edges) {
3+
if (n == 1) {
4+
return Arrays.asList(0);
5+
}
6+
7+
List<Set<Integer>> adjList = new ArrayList<>();
8+
List<Integer> leaves = new ArrayList<>();
9+
10+
for (int i = 0; i < n; i++) {
11+
adjList.add(new HashSet<>());
12+
}
13+
14+
for (int[] edge : edges) {
15+
adjList.get(edge[0]).add(edge[1]);
16+
adjList.get(edge[1]).add(edge[0]);
17+
}
18+
19+
for (int i = 0; i < n; i++) {
20+
if (adjList.get(i).size() == 1) {
21+
leaves.add(i);
22+
}
23+
}
24+
25+
while (n > 2) {
26+
n -= leaves.size();
27+
List<Integer> newLeaves = new ArrayList<>();
28+
29+
for (int currLeaf : leaves) {
30+
int adjLeaf = adjList.get(currLeaf).iterator().next();
31+
adjList.get(adjLeaf).remove(currLeaf);
32+
if (adjList.get(adjLeaf).size() == 1) {
33+
newLeaves.add(adjLeaf);
34+
}
35+
}
36+
37+
leaves = newLeaves;
38+
}
39+
40+
return leaves;
41+
}
42+
}

0 commit comments

Comments
 (0)