题解 | #把二叉树打印成多行#

把二叉树打印成多行

https://www.nowcoder.com/practice/445c44d982d04483b04a54f298796288

/* function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
} */
var res =[];//存最后结果
function bfs(root){
    let queue = [];//队列,负责出队 入队
    if(root == null){
        return null;
    }
    queue.push(root);
    //双层循环
    while(queue.length > 0){
        let temp = []// 存每一层的数字
        let n = queue.length;
        //遍历当前队列中的元素,也就是等于当前层的元素
        for(let i=0;i<n;i++){
            let node = queue.shift();
            temp.push(node.val)
            if(node.left != null){
                queue.push(node.left);
            }
            if(node.right != null){
                queue.push(node.right);
            } 
        }
        res.push(temp)
    }
}
function Print(pRoot)
{
    // write code here
    if(pRoot == null){
        return [];
    }
    bfs(pRoot)
    return res
    
}
module.exports = {
    Print : Print
};

#我的实习求职记录#
全部评论

相关推荐

2025-12-18 14:15
已编辑
哈尔滨工程大学 前端工程师
牛客87317764...:最近没啥hc,做好心灰意冷的准备。另外,大概率只有字节给你面试,最好别作为处女面
实习简历求拷打
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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