Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d82861b

Browse files
add LeetCode 102. 二叉树的层序遍历
1 parent c7a0383 commit d82861b

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
![](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9jZG4uanNkZWxpdnIubmV0L2doL2Nob2NvbGF0ZTE5OTkvY2RuL2ltZy8yMDIwMDgyODE0NTUyMS5qcGc?x-oss-process=image/format,png)
2+
>仰望星空的人,不应该被嘲笑
3+
4+
## 题目描述
5+
给你一个二叉树,请你返回其按 **层序遍历** 得到的节点值。 (即逐层地,从左到右访问所有节点)。
6+
7+
8+
9+
示例:
10+
11+
```javascript
12+
二叉树:[3,9,20,null,null,15,7],
13+
14+
3
15+
/ \
16+
9 20
17+
/ \
18+
15 7
19+
```
20+
21+
返回其层次遍历结果:
22+
23+
```javascript
24+
[
25+
[3],
26+
[9,20],
27+
[15,7]
28+
]
29+
```
30+
31+
来源:力扣(LeetCode)
32+
链接:https://leetcode-cn.com/problems/binary-tree-level-order-traversal
33+
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
34+
35+
36+
## 解题思路
37+
直接用 `BFS`,对于每一层初始化空数组,然后存放每一层的节点值,然后迭代即可。
38+
39+
```javascript
40+
/**
41+
* Definition for a binary tree node.
42+
* function TreeNode(val) {
43+
* this.val = val;
44+
* this.left = this.right = null;
45+
* }
46+
*/
47+
/**
48+
* @param {TreeNode} root
49+
* @return {number[][]}
50+
*/
51+
var levelOrder = function (root) {
52+
if(!root) return [];
53+
let res = [];
54+
let queue = [root];
55+
let cnt = 0;
56+
while (queue.length) {
57+
let size = queue.length;
58+
// 每一层初始化一个空数组
59+
res.push([]);
60+
while (size--) {
61+
let node = queue.shift();
62+
// 每一层的节点都存着
63+
res[cnt].push(node.val);
64+
node.left && queue.push(node.left);
65+
node.right && queue.push(node.right);
66+
}
67+
// 迭代层次
68+
++cnt;
69+
}
70+
return res;
71+
};
72+
```
73+
74+
## 最后
75+
文章产出不易,还望各位小伙伴们支持一波!
76+
77+
往期精选:
78+
79+
<a href="https://github.com/Chocolate1999/Front-end-learning-to-organize-notes">小狮子前端の笔记仓库</a>
80+
81+
<a href="https://github.com/Chocolate1999/leetcode-javascript">leetcode-javascript:LeetCode 力扣的 JavaScript 解题仓库,前端刷题路线(思维导图)</a>
82+
83+
小伙伴们可以在Issues中提交自己的解题代码,🤝 欢迎Contributing,可打卡刷题,Give a ⭐️ if this project helped you!
84+
85+
86+
<a href="https://yangchaoyi.vip/">访问超逸の博客</a>,方便小伙伴阅读玩耍~
87+
88+
![](https://img-blog.csdnimg.cn/2020090211491121.png#pic_center)
89+
90+
```javascript
91+
学如逆水行舟,不进则退
92+
```
93+
94+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /