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

把二叉树打印成多行

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

// 解题思路:bfs
// 使用队列来存储节点值
// 注意特殊输入,比如空树的情况
/*
 * function TreeNode(x) {
 *   this.val = x;
 *   this.left = null;
 *   this.right = null;
 * }
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 *
 * @param pRoot TreeNode类
 * @return int整型二维数组
 */
function Print(pRoot) {
    // write code here
    if(pRoot==null)return [];
    const queue = [pRoot];
    const result = [];
    let subResult;
    while (queue.length) {
        // 记得要重置一下
        console.log(queue.length);
        subResult = [];
        const len=queue.length;
        // 注意for中的len是会重新计算的,需要提前存下来,如果你写成queue.length的话,则是会影响遍历次数,导致错误
        for (let i = 0; i < len; i++) {
            const root = queue.shift();
            subResult.push(root.val);
            root.left && queue.push(root.left);
            root.right && queue.push(root.right);
        }
        console.log(subResult);
        result.push(subResult);
    }
    return result;
}
module.exports = {
    Print: Print,
};

全部评论

相关推荐

07-15 00:33
江苏大学 Java
代码飞升:哈哈哈哈评论区三个打广告的
简历中的项目经历要怎么写
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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