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

按之字形顺序打印二叉树

https://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 []
    }
    let odd = []
    let even = []
    let index = 1
    let resArr = []
    odd.push(pRoot)
    while(odd.length || even.length){
        if(index % 2 == 1){
            let temp = []
            while(odd.length){
                let node = odd.pop()
                temp.push(node.val)
                if(node.left){
                    even.push(node.left)
                }
                if(node.right){
                    even.push(node.right)
                }
            }
            index++
            resArr.push(temp)
        }
        else{
            let temp = []
            while(even.length){
                let node = even.pop()
                temp.push(node.val)
                if(node.right){
                    odd.push(node.right)
                }
                if(node.left){
                    odd.push(node.left)
                }

            }
            resArr.push(temp)
            index++
        }
        
    }
    return resArr
}
module.exports = {
    Print : Print
};

全部评论

相关推荐

LZHR:老哥你从投递简历测评完到一面中间隔了多久呀,我这边已经过了五天了仍显示简历筛选中是不是就是挂了
腾讯求职进展汇总
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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