题目描述:从上往下打印二叉树
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
题目解析:
利用队列的先进先出的特性。
利用辅助队列,将root,push进辅助队列,之后每次去除辅助队列的第一个元素进行,存值,并且对其左右节点进行判断。
完整代码:
/* function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
} */
function PrintFromTopToBottom(root)
{
// write code here
if (!root) return []
const queue = []
const res = []
queue.push(root)
while (queue.length !== 0){
let node = queue.shift()
if (node.left) {
queue.push(node.left)
}
if (node.right) {
queue.push(node.right)
}
res.push(node.val)
}
return res
}