题目描述:

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



知识点:

  • 深度优先与广度优先遍历过程中层数的统计

解题思路:

  • 这道题和59.按之字形顺序打印二叉树思路几乎是一摸一样,而且要简单,这道题我们不需要考虑打印顺序的问题直接按照广度优先遍历来便好,记得要统计层数
  • 同样我们可以使用递归版来一次,不过递归版使用的深度优先遍历的理念,也就是说如果我们要统计遍历的层数,我们可以使用深度优先与广度优先都可

解题代码:

  • 广度优先非递归版

    1. // 广度优先非递归版
    2. function Print(pRoot)
    3. {
    4. // write code here
    5. if(!pRoot) return [];
    6. const res = [];
    7. const queue = [[pRoot,0]];
    8. while (queue.length) {
    9. let [temp,l] = queue.shift();
    10. if(!res[l]) {
    11. res[l] = [];
    12. res[l].push(temp.val);
    13. }else {
    14. res[l].push(temp.val);
    15. }
    16. if(temp.left) queue.push([temp.left,l+1]);
    17. if(temp.right) queue.push([temp.right,l+1]);
    18. }
    19. return res;
    20. }
  • 深度优先递归版

    // 深度优先递归版
    function Print(pRoot)
    {
      // write code here
      if(!pRoot) return [];
      const res = [];
      const dfs = (node,deep) => {
          if(!res[deep]) {
              res[deep] = [];
              res[deep].push(node.val);
          }else {
              res[deep].push(node.val);
          }
          if(node.left) bfs(node.left,deep+1);
          if(node.right) bfs(node.right,deep+1);
      }
      bfs(pRoot,0);
      return res;
    }