Skip to content

102. 二叉树的层序遍历

给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。

示例 1:

img

输入:root = [3,9,20,null,null,15,7]
输出:[[3],[9,20],[15,7]]

示例 2:

输入:root = [1]
输出:[[1]]

示例 3:

输入:root = []
输出:[]

提示:

  • 树中节点数目在范围 [0, 2000]
  • -1000 <= Node.val <= 1000

一、解题

typescript
// https://leetcode.cn/problems/binary-tree-level-order-traversal/

import TreeNode from "../1-data-structure/TreeNode";
import BinaryTree from "../1-data-structure/BinaryTree";

function levelOrder(root: TreeNode | null): number[][] {
  if (!root) return [];
  const nodeList = [root];
  const result = [];
  let continueExecute = true;
  while (continueExecute) {
    const nextNodeList = [];
    const tempResult = [];
    continueExecute = false;
    for (let i = 0; i < nodeList.length; i++) {
      if (nodeList[i]) {
        tempResult.push(nodeList[i].val);
        nextNodeList.push(nodeList[i].left);
        nextNodeList.push(nodeList[i].right);
      }
      if (nodeList[i] && (nodeList[i].left || nodeList[i].right)) {
        continueExecute = true;
      }
    }
    result.push(tempResult);
    nodeList.length = 0;
    nodeList.push(...nextNodeList);
  }
  return result;
};

// [3,9,20,null,null,15,7]

const binaryTree = new BinaryTree();
binaryTree.append(3).append(9).append(20).append(null).append(null).append(15).append(7);

console.log(JSON.stringify(binaryTree.root, null, 4))