leetcode-Day9

从零开始Leetcode – Day 9

##Binary Tree Zigzag Level Order Traversal

这题和Binary Tree Level Order Traversal 很想。 要注意count是从第二层开始算。
Binary Tree Zigzag Level Order Traversal
广度优先的WIKI
https://en.wikipedia.org/wiki/Breadth-first_search
明早再练习这两题。

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

/**
* 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) {
var res = [];
if(!root){
return res;
}
var queue = [];
queue.push(root);

var curNum = 0;
var lastNum = 1;
var list = [];
var count = 0;
while(queue.length){

var cur = queue.shift();
lastNum --;
list.push(cur.val);
if(cur.left !== null){
queue.push(cur.left);
curNum++;
}
if(cur.right !== null){
queue.push(cur.right);
curNum ++;
}
if(lastNum === 0){
lastNum = curNum;
curNum = 0;
count = count +1;
if(count%2 === 0){
list.reverse();
}
res.push(list);
list = [];
}
}
return res;
};