题解 | #从上往下打印二叉树#

从上往下打印二叉树

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,
};

全部评论

相关推荐

不愿透露姓名的神秘牛友
05-28 12:15
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务