剑指offer(60)把二叉树打印成多行

题目描述

从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。

 

题目分析

从上到下打印二叉树我们知道用队列可以实现,但是如果多行打印怎么做呢?

我们需要分割,在行与行之间进行分割。如何分割呢?肯定要知道个数才能分割。

可是我又如何知道这一行有多少个呢?

这就是重点了,我们可以通过遍历上一层,通过它们的子树就可以知道这一层有多少个节点了。

当然我们还需要有一个变量来记录这一层已经打印了多少个节点了。

所以我们需要一个队列+两个个变量。

 

代码

function Print(pRoot) {
  const queue = [],
    res = [];
  if (pRoot === null) {
    return res;
  }
  queue.push(pRoot);
  let nextLevel = 0; // 下一层节点个数
  let toBePrinted = 1; // 这一层还有多少个节点要打印
  let list = []; // 存放每一层节点
  while (queue.length) {
    const pNode = queue.shift();
    list.push(pNode.val);
    if (pNode.left !== null) {
      queue.push(pNode.left);
      nextLevel++;
    }
    if (pNode.right !== null) {
      queue.push(pNode.right);
      nextLevel++;
    }
    toBePrinted--;
    if (toBePrinted === 0) {
      res.push(list);
      list = [];
      toBePrinted = nextLevel;
      nextLevel = 0;
    }
  }
  return res;
}

 

posted @ 2018-08-25 21:21  汕大小吴  阅读(770)  评论(0编辑  收藏  举报