Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
wangenze267 committed Mar 26, 2024
1 parent b81a6a5 commit f34faa6
Showing 1 changed file with 34 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,37 @@

而这种层序遍历方式就是广度优先遍历,只不过我们将用在图上的东西应用在了二叉树上。

## 开始刷题
### 二叉树的层序遍历

题目:[102.二叉树的层序遍历](https://leetcode.cn/problems/binary-tree-level-order-traversal/)

小 tips 🎗️:这个题算是层序遍历的模板题噢 ~ 务必牢记在心 !!!

```js
const ret = [];
if (!root) {
return ret;
}
const queue = [];
queue.push(root);
while (queue.length !== 0) {
ret.push([]);
let length = queue.length
for (let i = 1; i <= length; i++) {
const cur = queue.shift();
ret[ret.length - 1].push(cur.val);
if (cur.left){
queue.push(cur.left);
}
if (cur.right){
queue.push(cur.right);
}
}
}
return ret;
```

题目:[107.二叉树的层序遍历II](https://leetcode.cn/problems/binary-tree-level-order-traversal-ii/description/)

这道题跟上一题相比,就是将最终的结果进行了一个翻转,利用 `reverse` 即可,代码就不再重复了。

0 comments on commit f34faa6

Please sign in to comment.