-
Notifications
You must be signed in to change notification settings - Fork 41
/
solution.js
36 lines (35 loc) · 881 Bytes
/
solution.js
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
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[][]}
*/
// 层序遍历
var zigzagLevelOrder = function (root) {
const result = [];
if (root === null) {
return result;
}
let curLevel = [
root, ];
while (true) {
const nextLevel = [];
const values = [];
for (let i = 0; i < curLevel.length; i++) {
values.push(curLevel[i].val);
curLevel[i].left && nextLevel.push(curLevel[i].left);
curLevel[i].right && nextLevel.push(curLevel[i].right);
}
result.length % 2 === 1 && values.reverse();
result.push(values);
if (nextLevel.length === 0) {
return result;
}
curLevel = nextLevel;
}
};