从上到下打印二叉树 III
请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。
例如:
给定二叉树: [3,9,20,null,null,15,7]
3
/ \
9 20
/ \
15 7
1
2
3
4
5
2
3
4
5
返回其层次遍历结果:
[
[3],
[20,9],
[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 = []
let right = false
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++) {
right ? curAns.unshift(curr[i].val) : curAns.push(curr[i].val)
if (curr[i].left) {
prev.push(curr[i].left)
}
if (curr[i].right) {
prev.push(curr[i].right)
}
}
right = !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
39
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
39
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-iii-lcof