Skip to content

Commit 56a4576

Browse files
Sean PrashadSean Prashad
authored andcommitted
Update 310_Minimum_Height_Trees.java
1 parent 92b47b5 commit 56a4576

File tree

1 file changed

+21
-18
lines changed

1 file changed

+21
-18
lines changed

Topological Sort/310_Minimum_Height_Trees.java

Lines changed: 21 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -4,33 +4,36 @@ public List<Integer> findMinHeightTrees(int n, int[][] edges) {
44
return Arrays.asList(0);
55
}
66

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-
}
7+
Map<Integer, Set<Integer>> graph = new HashMap<>();
138

149
for (int[] edge : edges) {
15-
adjList.get(edge[0]).add(edge[1]);
16-
adjList.get(edge[1]).add(edge[0]);
10+
graph.putIfAbsent(edge[0], new HashSet<>());
11+
graph.putIfAbsent(edge[1], new HashSet<>());
12+
13+
graph.get(edge[0]).add(edge[1]);
14+
graph.get(edge[1]).add(edge[0]);
1715
}
1816

19-
for (int i = 0; i < n; i++) {
20-
if (adjList.get(i).size() == 1) {
21-
leaves.add(i);
17+
List<Integer> leaves = new ArrayList<>();
18+
19+
for (int leaf : graph.keySet()) {
20+
if (graph.get(leaf).size() == 1) {
21+
leaves.add(leaf);
2222
}
2323
}
2424

25-
while (n > 2) {
26-
n -= leaves.size();
25+
int remainingNodes = n;
26+
27+
while (remainingNodes > 2) {
28+
remainingNodes -= leaves.size();
2729
List<Integer> newLeaves = new ArrayList<>();
2830

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);
31+
for (int leaf : leaves) {
32+
int neighbour = graph.get(leaf).iterator().next();
33+
graph.get(neighbour).remove(leaf);
34+
35+
if (graph.get(neighbour).size() == 1) {
36+
newLeaves.add(neighbour);
3437
}
3538
}
3639

0 commit comments

Comments
 (0)