首页 > 其他 > 详细

树---按之字形打印二叉树

时间:2020-04-04 17:29:48      阅读:53      评论:0      收藏:0      [点我收藏+]

请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。

分析:https://blog.csdn.net/qq_40608516/article/details/91128825

/* function TreeNode(x) {

    this.val = x;

    this.left = null;

    this.right = null;

} */

function Print(pRoot)

{

    // write code here

    const lists=[]

    if(pRoot===null){

        return lists

    }

    const stack1=[],stack2=[]

    let i=1

    stack2.push(pRoot)

    while(stack1.length!==0||stack2.length!==0){

        const list=[]

        //为奇数层

        if((i % 2) === 1){

            while(stack2.length!==0){

                const temp=stack2[stack2.length-1]

                stack2.pop()

                list.push(temp.val)

                if(temp.left!==null)stack1.push(temp.left)

                if(temp.right!==null)stack1.push(temp.right)

            }

        }else{

             while(stack1.length!=0){

                const temp=stack1[stack1.length-1]

                stack1.pop()

                list.push(temp.val)

                if(temp.right!==null)stack2.push(temp.right)

                if(temp.left!==null)stack2.push(temp.left)

            }

        }

        i++

        lists.push(list)

    }

    return lists

}

 

树---按之字形打印二叉树

原文:https://www.cnblogs.com/mlebk/p/12632495.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!