103. 二叉树的锯齿形层序遍历
给定一个二叉树,返回其节点值的锯齿形层序遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
链接
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
   | function zigzagLevelOrder(root: TreeNode | null): number[][] {   if (root === null) return []   const nodeList: Array<TreeNode | null> = [root]   let isResverse = false   const res = []   while(nodeList.length > 0) {     const method = isResverse ? Array.prototype.unshift : Array.prototype.push     isResverse = !isResverse     if (nodeList.length === 1) {       const parent = nodeList.shift()       nodeList.push(parent.left)       nodeList.push(parent.right)       res.push([parent.val])     } else {       const nodeL = nodeList.splice(0)       const len = nodeL.length       const valList = []       for(let i = 0; i < len;i++) {         const node = nodeL[i]         if (node) {           method.call(valList, node.val)           nodeList.push(node.left)           nodeList.push(node.right)         }       }       valList.length > 0 && res.push(valList)     }   }   return res }
  |