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

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

分析: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

}

 

posted @ 2020-04-04 16:48  mle123  阅读(224)  评论(0编辑  收藏  举报