forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.ts
34 lines (34 loc) · 861 Bytes
/
Solution.ts
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
function findMinHeightTrees(n: number, edges: number[][]): number[] {
if (n === 1) {
return [0];
}
const g: number[][] = Array.from({ length: n }, () => []);
const degree: number[] = Array(n).fill(0);
for (const [a, b] of edges) {
g[a].push(b);
g[b].push(a);
++degree[a];
++degree[b];
}
const q: number[] = [];
for (let i = 0; i < n; ++i) {
if (degree[i] === 1) {
q.push(i);
}
}
const ans: number[] = [];
while (q.length > 0) {
ans.length = 0;
const t: number[] = [];
for (const a of q) {
ans.push(a);
for (const b of g[a]) {
if (--degree[b] === 1) {
t.push(b);
}
}
}
q.splice(0, q.length, ...t);
}
return ans;
}