Skip to content

Commit 71678f3

Browse files
authored
Update 310-minimum-height-trees.js
1 parent 46be45b commit 71678f3

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

310-minimum-height-trees.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,42 @@
1+
/**
2+
* @param {number} n
3+
* @param {number[][]} edges
4+
* @return {number[]}
5+
*/
6+
const findMinHeightTrees = function (n, edges) {
7+
const hash = {}
8+
9+
for(const [u, v] of edges) {
10+
if(graph[u] == null) graph[u] = new Set()
11+
if(graph[v] == null) graph[v] = new Set()
12+
graph[u].add(v)
13+
graph[v].add(u)
14+
}
15+
16+
let q = []
17+
for(let i = 0; i < n; i++) {
18+
if(hash[i].size === 1) q.push(i)
19+
}
20+
21+
while(n > 2) {
22+
const size = q.length, nxt = []
23+
n -= size
24+
for(let i = 0; i < size; i++) {
25+
const cur = q[i]
26+
for(const e of (hash[cur] || [])) {
27+
graph[e].delete(cur)
28+
if(graph[e].size === 1) nxt.push(e)
29+
}
30+
}
31+
32+
q = nxt
33+
}
34+
35+
return q
36+
}
37+
38+
// another
39+
140
/**
241
* @param {number} n
342
* @param {number[][]} edges

0 commit comments

Comments
 (0)