剑指 offer 树算法题:从上到下打印二叉树

题目描述:从上往下打印出二叉树的每个节点。分为三种情况:

  1. 顺序打印一维数组(同层从左往右)
  2. 顺序打印二维数组(同层从左往右为一维数组)
  3. 之字形打印二维数组(同层交替方向)。

分析:

由题目分析,是层序遍历的过程,因此直接层序遍历即可,如果要求返回的是二维数组,即每一层节点数组构成的数组,仅仅需要在每一层遍历开始构建数组,遍历完该层后将数组加入到外层数组中。还有就是可能要求之字形的打印(即偶数层的打印是从右到左),使用一个层遍历初始方向标志变量,对于每一层true则push,false则unshift,该变量初始为true,每打印一层取反,遍历完该层后将数组加入到外层数组中即可。

求解

// 一维数组
function levelOrder1(root: TreeNode<number> | null): number[] {
  if (root === null) return [];
  const result: number[] = [];
  const queue = [root]; // 队列(先入先出)
  while (queue.length !== 0) {
    // 队列非空
    const current = queue.shift()!; // 队首出队
    result.push(current.val);
    const leftChild = current.left;
    const rightChild = current.right;
    if (leftChild !== null) queue.push(leftChild);
    if (rightChild !== null) queue.push(rightChild);
  }
  return result;
}

// 二维数组
function levelOrder2(root: TreeNode<number> | null): number[][] {
  if (root === null) return [];
  const result: number[][] = [];
  const queue = [root]; // 队列(先入先出)
  while (queue.length !== 0) {
    const size = queue.length;
    // 当前层的节点
    const arr: number[] = [];
    for (let i = 0; i < size; i++) {
      const node = queue.shift()!;
      const leftChild = node.left;
      const rightChild = node.right;
      arr.push(node.val);
      if (leftChild !== null) queue.push(leftChild);
      if (rightChild !== null) queue.push(rightChild);
    }
    result.push(arr);
  }
  return result;
}

// 之字形打印(二维数组)
function levelOrder3(root: TreeNode<number> | null): number[][] {
  if (root === null) return [];
  const result: number[][] = [];
  const queue = [root]; // 队列(先入先出)
  let isOrderLeft = true;
  while (queue.length !== 0) {
    const size = queue.length;
    // 当前层的节点
    const arr: number[] = [];
    for (let i = 0; i < size; i++) {
      const node = queue.shift()!;
      const leftChild = node.left;
      const rightChild = node.right;
      isOrderLeft ? arr.push(node.val) : arr.unshift(node.val);
      if (leftChild !== null) queue.push(leftChild);
      if (rightChild !== null) queue.push(rightChild);
    }
    result.push(arr);
    isOrderLeft = !isOrderLeft;
  }
  return result;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

薛定谔的猫96

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值