从上往下打印出二叉树的每个节点,同层节点从左至右打印。
利用队列的先进先出的特性。
利用辅助队列,将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
}
本文地址:https://blog.csdn.net/qq_43955202/article/details/107306069
如对本文有疑问, 点击进行留言回复!!
offset、client、scroll (width,height、left,top、X,Y)
网友评论