102. 二叉树的层序遍历
给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。
链接
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
   | function levelOrder(root: TreeNode | null): number[][] {   if (root === null) return []   const nodeList: Array<TreeNode | null> = [root]   const res = []   while(nodeList.length > 0) {     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) {           valList.push(node.val)           nodeList.push(node.left)           nodeList.push(node.right)         }       }       valList.length > 0 && res.push(valList)     }   }   return res }
  |