跳至主要內容

广度优先遍历

yyshino小于 1 分钟FrontEnd浏览器

广度优先遍历 - 层序遍历

思路:

  /**
   * Definition for a binary tree node.
   * class TreeNode {
   *     val: number
   *     left: TreeNode | null
   *     right: TreeNode | null
   *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
   *         this.val = (val===undefined ? 0 : val)
   *         this.left = (left===undefined ? null : left)
   *         this.right = (right===undefined ? null : right)
   *     }
   * }
   */

  function levelOrder(root: TreeNode | null): number[][] {
      if(!root){
          return []
      }

      let ans = []
      let cur = [root]
      while(cur.length){
          let nxt = []
          let vals = []
          for(const node of cur){
              vals.push(node.val)
              if(node.left) nxt.push(node.left)
              if(node.right) nxt.push(node.right)
          }
          cur = nxt
          ans.push(vals)
      }
      return ans
  };