Print the Binary Tree in Zigzag Order

Posted: February 13, 2011 in Algorithms, data structures, Microsoft

Q. Given a binary tree, you have to print it in zigzag order of breadth first traversal. For example

Should be printed as  {A, B, C, G, F, E, D, H, I, J, K , L, M}

A. We have to use two stacks for doing this operation

  • At every level, we will push the nodes in one stack and print them.
  • At every push, print the node.
  • At every pop, push the children in another stack.
  • When the stack is empty change the traversal direction. i.e. if its left and then right node, it will be changed as right and then left node.

For example, above stack will result in following operation

  • Push A in stack 1. A printed.
  • Pop A and push B n C in stack 2. B and C printed. Direction is left -> right.
  • Change the direction and child stack reference. Direction becomes right -> left and stack 1 becomes the new child stack.
  • Pop C, this will print and push G and C. Since direction is right, left now, G is taken up first.
  • Similar operation keeps repeating till both stacks are empty.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s