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

按之字形顺序打印二叉树

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

/* function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
} */
function Print(pRoot)
{
    // write code here
    if(pRoot == null) return [];
    const queue=[pRoot];
    let depth=0;
    const res=[];
    
    while(queue.length>0){
        let level=[];
        let size=queue.length;
        while(size--){
            const cur=queue.shift();
            depth % 2 === 0 ?level.push(cur.val):level.unshift(cur.val);
            if(cur.left){
                queue.push(cur.left);
            }
            
            if(cur.right){
                queue.push(cur.right);
            }
        }
        
        depth++;
        
        res.push(level);
    }
    
    return res;
}
module.exports = {
    Print : Print
};
全部评论

相关推荐

用微笑面对困难:你出于礼貌叫了人一声大姐,大姐很欣慰,她真把你当老弟
点赞 评论 收藏
分享
职场水母:为啥你们整简历都喜欢整一大堆没用的,是期待让hr觉得很多,自己很厉害吗
0offer是寒冬太冷还...
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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