题目
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
思路
广度优先遍历,利用队列的思想,先进先出
代码
/* function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
} */
function PrintFromTopToBottom(root) {
const queue = [],
res = [];
if (root === null) {
return res;
}
queue.push(root);
while (queue.length) {
const pRoot = queue.shift();
if (pRoot.left !== null) {
queue.push(pRoot.left);
}
if (pRoot.right !== null) {
queue.push(pRoot.right);
}
res.push(pRoot.val);
}
return res;
}