Skip to content
This repository has been archived by the owner on May 3, 2024. It is now read-only.

Commit

Permalink
leetcode: finished #310
Browse files Browse the repository at this point in the history
  • Loading branch information
xqm32 committed Feb 28, 2024
1 parent 8c80871 commit 08cb5a7
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions content/leetcode/2024/2.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,55 @@ title: 2024.2
draft: false
---

# 2024.2.28

```typescript
/*
* @lc app=leetcode.cn id=310 lang=typescript
*
* [310] 最小高度树
*/

// @lc code=start
function findMinHeightTrees(n: number, edges: number[][]): number[] {
if (n === 1) return [0];

const graph: number[][] = Array.from({ length: n }, () => []);
const degree: number[] = Array.from({ length: n }, () => 0);

for (let [a, b] of edges) {
graph[a].push(b);
graph[b].push(a);
degree[a]++;
degree[b]++;
}

const queue: number[] = [];
for (let i = 0; i < n; i++) {
if (degree[i] === 1) {
queue.push(i);
}
}

while (n > 2) {
const size = queue.length;
n -= size;
for (let i = 0; i < size; i++) {
const node = queue.shift()!;
for (let neighbor of graph[node]) {
degree[neighbor]--;
if (degree[neighbor] === 1) {
queue.push(neighbor);
}
}
}
}

return queue;
}
// @lc code=end
```

# 2024.2.27

```typescript
Expand Down

0 comments on commit 08cb5a7

Please sign in to comment.