We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 46be45b commit 71678f3Copy full SHA for 71678f3
310-minimum-height-trees.js
@@ -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
40
/**
41
* @param {number} n
42
* @param {number[][]} edges
0 commit comments