Spiral/Zigzag level order traversal of binary tree in java

If you want to practice data structure and algorithm programs, you can go through data structure and algorithm interview questions.

This is 6th part of java binary tree tutorial.

In this post, we will see about Spiral/Zigzag Level Order binary tree traversal in java.

Spiral/Zigzag Level Order traversal:

Spiral/Zigzag Level order traversal of below tree will be:

Steps for solution:

  1. Create an empty stack s and push root to it.
  2. while stack is not NULL Do following
    1. Create a empty stack called tempStack.
    2. Pop a node from stack and push it to tempStack depending on directionFlag
    3. Change directionFlag to change the direction of traversal
    4. set stack=tempStack

Lets say your binary tree is :

So Spiral/Zigzag Level Order traversal will work as below:

Lets create java program for Spiral/Zigzag Level traversal:

Run above program and you will get following output:

Java Binary tree tutorial:

Please go through java interview programs for more such programs.

Add Comment