Open pwstrick opened 4 years ago
103. 二叉树的锯齿形层次遍历
/** * 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) { if(!root) return []; const queue = [root], nodes = []; let depth = 0; while(queue.length > 0) { let len = queue.length; if(!nodes[depth]) { nodes[depth] = []; } if(depth % 2 == 0) { //从左往右 for(let i=0; i<len; i++) { nodes[depth].push(queue[i].val); } }else { //从右往左 for(let i=len-1; i>=0; i--) { nodes[depth].push(queue[i].val); } } for(let i=0; i<len; i++) { queue[i].left && queue.push(queue[i].left); queue[i].right && queue.push(queue[i].right); } queue.splice(0, len); depth++; } return nodes; };
103. 二叉树的锯齿形层次遍历