# 题目描述
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
# 测试用例
给定二叉树: [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) {
return [];
}
let nodes = [];
nodes.push(root);
let res = [];
// true表示从左到右
// false表示从右到左
let flag = true;
while (nodes.length) {
let temp = [];
let len = nodes.length;
for (let i = 0; i < len; i++) {
let cur = nodes.shift();
flag === true ? temp.push(cur.val) : temp.unshift(cur.val);
if (cur.left) {
nodes.push(cur.left);
}
if (cur.right) {
nodes.push(cur.right);
}
}
res.push(temp);
flag = !flag;
}
return res;
};
function TreeNode(val, left, right) {
this.val = val === undefined ? 0 : val;
this.left = left === undefined ? null : left;
this.right = right === undefined ? null : right;
}
var __readline = require("readline-sync");
__readline.setDefaultOptions({ prompt: "" });
var readline = __readline.prompt;
console.log("请输入二叉树数组");
const a = readline()
.split(",")
.map((item) => {
if (item == "null") {
return null;
} else {
return Number(item);
}
});
let arr = [];
// 二叉树数组内的值转为TreeNode
for (let i = 0; i < a.length; i++) {
arr[i] = new TreeNode(a[i]);
}
// 构造二叉树
for (let i = 0; i <= arr.length / 2 + 1; i++) {
if (arr[2 * i + 1]) {
if (arr[2 * i + 1].val != null) {
arr[i].left = arr[2 * i + 1];
}
}
if (arr[2 * i + 2]) {
if (arr[2 * i + 2].val != null) {
arr[i].right = arr[2 * i + 2];
}
}
}
const res = levelOrder(arr[0]);
console.log("结果为: ", res);
/*
请输入二叉树数组
3,9,20,null,null,15,7
结果为: [ [ 3 ], [ 20, 9 ], [ 15, 7 ] ]
*/
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91