# 题目描述
从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
例如: 给定二叉树: [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
# 思路
记录栈中节点元素的个数,作为当前层的节点个数,用来变量每一层的节点
# 代码实现
var __readline = require("readline-sync");
__readline.setDefaultOptions({ prompt: "" });
var readline = __readline.prompt;
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
function TreeNode(val) {
this.val = val;
this.left = this.right = null;
}
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];
}
}
}
console.log(arr);
/**
*
*
* @param {TreeNode} root
* @return {number[][]}
*/
var levelOrder = function (root) {
if (!root) {
return [];
}
// 记录下一层结点的个数
let res = [];
let levelRes = [];
let nodes = [];
nodes.push(root);
let cnt = 1;
let nextCnt = 0;
while (nodes.length > 0) {
/* while(nodes.length > 0 && cnt > 0){
// 放入层结果
let cur = nodes.shift();
levelRes.push(cur.val);
if(cur.left){
nodes.push(cur.left);
nextCnt ++;
}
if(cur.right){
nodes.push(cur.right);
nextCnt ++;
}
cnt --;
}
// 放入最终结果
res.push(levelRes);
levelRes = [];
cnt = nextCnt;
nextCnt = 0; */
let len = nodes.length;
let level = [];
for (let i = 0; i < len; i++) {
let cur = nodes.shift();
// if (cur.val !== null) {
// level.push(cur.val);
// }
level.push(cur.val);
if (cur.left) {
nodes.push(cur.left);
nextCnt++;
}
if (cur.right) {
nodes.push(cur.right);
nextCnt++;
}
}
res.push(level);
}
return res;
};
const res = levelOrder(arr[0]);
console.log("结果为: ", res);
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114