Thursday 20 September, 2012

Q) How to print a binary tree in spiral direction (Zig Zag)

Example:

 If tree is      
                                   1

                           2               3

                      4       5         6   7

you've to print     1 2 3 7 6 5 4

We can achieve this by using 2 stacks, one for storing nodes while traversing from left to right, and other one for storing nodes while traversing from right to left.

//Have 2 stacks S1 and S2.
void printZigZag(node *root)
{
   node *ptr = NULL;
   int leftToRight = 1;
  S1.push(root);
  while (!S1.isEmpty() || !S2.isEmpty())
  {
       if (leftToRight)
       {
            while (!S1.isEmpty())
            {
               ptr = S1.pop();
               printf("%d", ptr->data);

               if (ptr->right)
                    S2.push(ptr->right);

               if (ptr->left)
                    S2.push(ptr->left);
            }
       } else {
            while (!S2.isEmpty())
            {
                ptr = S2.pop();
                printf("%d", ptr->data);
                if (ptr->left)
                     S1.push(ptr->left);

                if (ptr->right)
                     S1.push(ptr->right);

            }
       }
       leftToRight = 1 - leftToRight;
 }

No comments:

Post a Comment