剑指offer[22]——从上往下打印二叉树

题目描述

从上往下打印出二叉树的每个节点,同层节点从左至右打印。

这道题目就是要维护一个队列,以该队列不为空为条件进行循环,每次循环将队列底的元素弹出,然后将其元素的值压入res中,再向队列中压入该元素的左子树与右子数。

function PrintFromTopToBottom(root)
{
    let temp = [];
    let res = [];
    if(!root){return [];}
    temp.push(root);
    while (temp.length) {
      let _root = temp.shift();
      res.push(_root.val);
      if(_root.left){temp.push(_root.left);}
      if(_root.right){temp.push(_root.right);}
    }
    return res;
}
原文地址:https://www.cnblogs.com/Jacob98/p/12485302.html