Sunday, December 21, 2014

Spiral (ZigZag printing) Printing the Binary Tree nodes in C

This is a variant of level order printing. In level order printing we can use iterative or a queue based approach. Iterative option is still available in this one too.But we are trying to follow a non iterative approach here. Instead of a queue we will have two stacks for implementing Sprial printing (also called ZigZag printing) of the Binary Tree. First we push the root node to stack one. Then we visit both stacks and take the top item and store it in a temp variable, then we will pop the stack from which we had pushed the binary tree node. At the same time we will push into the alternate stack the children of the temporary node we had stored. On one stack we will push in right then left child order and in the other one we will be pushing in left and then right children order.

For a binary tree like below

                                         1
                                         / \
                                        2 3
                                       /\  /\
                                     4 5 6 7

 the spiral printing order will be as below:

 1
23
7654

 Below is the implementation:

No comments:

Post a Comment