Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

print level order traversal of binary tree in Zigzag manner

I have to print the nodes of a binary tree using level order traversal but in spiral form i.e nodes at different level should be printed in spiral form.

for eg: If the tree look like:

The output should be 10 5 20 25 15 6 4.

The algorithm i used is simple and is just a small variation of level order traversal. I just took a variable p.if the variable is equal to 1 than print the order at a given level left to right , if it is -1 print right to left.

void getlevel(struct node *root,int n,int p)
{
        if(root==NULL)
        return;
        if(n==0)
        {
                printf("%d ",root->info);
                return;
        }
        if(n>0)
        {
            if(p==1)
            {
                 getlevel(root->left,n-1,p);
                 getlevel(root->right,n-1,p);
            }
            if(p==-1)
            {
                 getlevel(root->right,n-1,p);
                 getlevel(root->left,n-1,p);
            }
        }
}

I am getting the answer but the worst case complexity is probably O(n^2) in case of skewed tree.

Can there be a better algorithm for this task?..

My entire program is here

like image 687
poorvank Avatar asked Jul 05 '13 09:07

poorvank


People also ask

What is zigzag level order traversal?

The zigzag level order traversal of a binary tree covers all the nodes of the tree such that each level is traversed left to right or right to left alternatively. Given the root node of a binary tree, return an array depicting the zigzag level order traversal.

What is zigzag traversal of binary tree?

The zigzag traversal of a binary tree means for the node at the top level we go from left to right, then for the next level, we go from right to left, and thus, we keep on changing the direction from left to right, and then from right to left.


1 Answers

Yes.

You can do something similar to normal level order traversal.

You have to use two stacks

  1. first stack for printing from left to right
  2. second stack for printing from right to left.

Start from the root node. Store it's children in one stack. In every iteration, you have nodes of one level in one of the stacks. Print the nodes, and push nodes of next level in other stack. Repeat until your reach the final level.

Time Complexity O(n) and space complexity O(n).

like image 103
banarun Avatar answered Sep 18 '22 14:09

banarun