白菜刷LeetCode记-103. Binary Tree Zigzag Level Order Traversal

今天的题目是对昨天题目的加深印象,题目如下:

有了昨天的答案,今天做得就比较轻松了,代码如下:

 

 1 /**
 2  * Definition for a binary tree node.
 3  * function TreeNode(val) {
 4  *     this.val = val;
 5  *     this.left = this.right = null;
 6  * }
 7  */
 8 /**
 9  * @param {TreeNode} root
10  * @return {number[][]}
11  */
12 var zigzagLevelOrder = function(root) {
13     let res = new Array();
14     
15     helper(root, res, 0);
16     
17     for(let i = 0 ; i < res.length ; i++){
18         if(i%2){
19             res[i].reverse();
20         }
21     }
22     
23     return res;
24 };
25 
26 var helper = function(root, res, level){
27     if(root == null)  return;
28     
29     if(res.length < level + 1){
30         res.push([]);
31     }
32     
33     helper(root.left, res, level + 1);
34     helper(root.right, res, level + 1);
35     
36     res[level].push(root.val);
37 }

 

posted @ 2018-09-26 11:32  sysu_kww  阅读(116)  评论(0编辑  收藏  举报