题解 | #按之字形顺序打印二叉树#

按之字形顺序打印二叉树

https://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0

/* function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
} */
function Print(pRoot)
{
    // write code here
    const cengxu = BreadthTraverse(pRoot);
    const res = ZhiPrint(cengxu);
    return res;
}

function ZhiPrint(vector) {
    const res = [];
    for(let i = 0; i < vector.length; i++) {
        let temp = [];
        for(let j = 0; j < vector[i].length; j++) {
            if(i % 2 === 0) {
                temp.push(vector[i][j]);
            } else {
                temp.unshift(vector[i][j]);
            }
        }
        res.push(temp);
    };
    return res;
}

function BreadthTraverse(root) {
    if(!root) return [];

    const queue = [], res = [];
    
    queue.push(root);
    
    while(queue.length) {
        let size = queue.length;
        const temp = [];
        
        while(size--) {
            const node = queue.shift();
            temp.push(node.val);

            if(node.left) {
                queue.push(node.left);
            }

            if(node.right) {
                queue.push(node.right);
            }
        }
        res.push(temp);
    }
    return res;
}

module.exports = {
    Print : Print
};

这道题没啥说的,就是一个二叉树层序遍历的应用。

题目 ”之字形“ 的要求只需要在层序遍历后按特定的顺序重新组织一下二维数组即可,细心一点即可。

全部评论

相关推荐

lingo12:1.最好加个业务项目,大部分面试官工作以后会更偏重业务 2.实习部分描述一般般,可能hr看到会觉得你产出不够不给你过简历 3.蓝桥杯这些大部分人都有的,不如不写,反而减分项。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务