Tree --- zigzag print binary tree

Implement according to a zigzag print function binary tree, i.e., left to right, the first print line of the second layer in order to print from right to left, the third line from left to right order of printing, in other rows forth.

Analysis: 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

}

 

Guess you like

Origin www.cnblogs.com/mlebk/p/12632495.html