Spiral/Zigzag level order traversal of binary tree in java

If you want to practice data structure and algorithm programs, you can go through 100+ java coding 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
Example:
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.

import_contacts

You may also like:

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.