-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0310-minimum-height-trees.js
More file actions
37 lines (33 loc) · 1.07 KB
/
0310-minimum-height-trees.js
File metadata and controls
37 lines (33 loc) · 1.07 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
/**
* Minimum Height Trees
* Time Complexity: O(N)
* Space Complexity: O(N)
*/
var findMinHeightTrees = function (n, edges) {
if (n === 1) return [0];
const adjacencyLists = new Array(n).fill().map(() => new Set());
for (const [nodeOne, nodeTwo] of edges) {
adjacencyLists[nodeOne].add(nodeTwo);
adjacencyLists[nodeTwo].add(nodeOne);
}
let currentLeaves = [];
for (let indexCounter = 0; indexCounter < n; indexCounter++) {
if (adjacencyLists[indexCounter].size === 1) {
currentLeaves.push(indexCounter);
}
}
let totalNodesRemaining = n;
while (totalNodesRemaining > 2) {
totalNodesRemaining -= currentLeaves.length;
const nextIterationLeaves = [];
for (const processingLeaf of currentLeaves) {
const neighborOfLeaf = adjacencyLists[processingLeaf].values().next().value;
adjacencyLists[neighborOfLeaf].delete(processingLeaf);
if (adjacencyLists[neighborOfLeaf].size === 1) {
nextIterationLeaves.push(neighborOfLeaf);
}
}
currentLeaves = nextIterationLeaves;
}
return currentLeaves;
};