题解 | #从上往下打印二叉树#
从上往下打印二叉树
https://www.nowcoder.com/practice/7fe2212963db4790b57431d9ed259701
/* function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
} */
function PrintFromTopToBottom(root) {
// 层序遍历,广度优先搜索,使用队列
// queue模拟队列
let queue = [];
// 存储结果
let res = [];
if (!root) return res;
queue.push(root);
while (queue.length > 0) {
// 出队列并保存到res结果数组中
let node = queue.shift();
res.push(node.val);
// 将出队列的结点的左右孩子加入到队列中
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
return res;
}
module.exports = {
PrintFromTopToBottom: PrintFromTopToBottom,
};

