题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
解题思路
层次打印树,其实就是树的广度遍历,利用队列的FIFO的特点,从上到下从左到右打印结点。
Code
/* function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
} */
function PrintFromTopToBottom(root)
{
// write code here
if(!root) return [];
let queue=[],res=[];
queue.push(root);
while(queue.length!=0){
node=queue.shift();
res.push(node.val);
if(node.left) queue.push(node.left);
if(node.right) queue.push(node.right);
}
return res;
}
运行环境:JavaScript (V8 6.0.0)
运行时间:11ms
占用内存:5344k