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

按之字形顺序打印二叉树

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

    this.val = x;
    this.left = null;
    this.right = null;
} */
function Print(pRoot)
{
    // write code here
    let res=[]
    let d=0
    let d1=0
    let arr=[]
    if(pRoot!=null){
        let res1=[]
        res1.push(pRoot.val)
        res.push(res1)
        if(d==0){d=1;}
        else if(d==1){d=0;}
        arr.push(pRoot)
    }
    while(d1!=d){
        let res1=[]
        d1=d
        let arr2=findnext(d,arr)//d=0从右x=向左打印
        arr=arr2
        if(arr2.length==0){return res}
        else{
            for(let i=0;i<arr2.length;i++){
                res1.push(arr2[i].val)
            }
            if(d==0){d=1;}
            else if(d==1){d=0;}
            res.push(res1)
        }
     }
     return res
}
function findnext(d,arr){
    let res=[]
    if(d==1){
        for(let i=arr.length-1;i>=0;i--){
            if(arr[i].right!=null){res.push(arr[i].right)}
            if(arr[i].left!=null){res.push(arr[i].left)}
        }
    }
    else{
        for(let i=arr.length-1;i>=0;i--){
            if(arr[i].left!=null){res.push(arr[i].left)}
            if(arr[i].right!=null){res.push(arr[i].right)}
        }
    }
    return res
}
module.exports = {
    Print : Print
};

这道题终于过了。。每次输出下一次的节点数组(节点的信息量更大),val再循环取一遍就行

全部评论

相关推荐

湫湫湫不会java:1.在校经历全删了2.。这些荣誉其实也没啥用只能说,要的是好的开发者不是好好学生3.项目五六点就行了,一个亮点一俩行,xxx技术解决,xxx问题带来xxx提升。第一页学历不行,然后啥有价值的信息也没有,到第二页看到项目了,第一个项目九点,第二个项目像凑数的俩点。总体给人又臭又长,一起加油吧兄弟
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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