从上到下打印二叉树 II
从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
例如:
给定二叉树: [3,9,20,null,null,15,7]
3
/ \
9 20
/ \
15 7
1
2
3
4
5
2
3
4
5
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
1
2
3
4
5
2
3
4
5
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[][]}
*/
var levelOrder = function(root) {
if(root === null) return []
let queue = []
let ans = []
queue.push([root])
while (queue.length) {
let curr = queue.shift()
if (curr.length) {
let curAns = []
let prev = []
for (let i = 0; i < curr.length; i++) {
curAns.push(curr[i].val)
if (curr[i].left) {
prev.push(curr[i].left)
}
if (curr[i].right) {
prev.push(curr[i].right)
}
}
ans.push(curAns)
queue.push(prev)
}
}
return ans
};
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
35
36
37
38
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
35
36
37
38
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-ii-lcof