Level order traversal in spiral form

PROBLEM :


Write a function to print spiral order traversal of a tree. For below tree, function should print 1, 2, 3, 4, 5, 6, 7.

        




Input:
The task is to complete the method which takes one argument, root of the Tree. The struct node has a data part which stores the data, pointer to left child and pointer to right child.
There are multiple test cases. For each test case, this method will be called individually.

Output:
The function should print level order traversal in spiral form .

Constraints:
1 <=T<= 30
1 <=Number of nodes<= 100
1 <=Data of a node<= 1000

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

/* A binary tree node has data, pointer to left child
   and a pointer to right child
struct node
{
    int data;
    struct node* left;
    struct node* right;
}; */

int height(struct node *) ;
void print(struct node *,int,bool) ;


void printSpiral(struct node *root)
{
    if(root==NULL)
    return ;
    int h,i ;
    h=height(root) ;
    bool spiral=false ;
    for(i=1;i<=h;i++)
    {
       print(root,i,spiral) ;
       spiral=!spiral ;
    }
}

void print(struct node *root,int level,bool spiral)
{
    if(root==NULL)
        return ;
    if(level==1)
        cout<<root->data<<" " ;
    if(spiral==true)
    {
        print(root->left,level-1,spiral) ;
        print(root->right,level-1,spiral) ;
    }
    else
    {
        print(root->right,level-1,spiral) ;
        print(root->left,level-1,spiral) ;
    }
}

int height(struct node *root)
{
    if(root==NULL)
    return 0 ;
 
    int L,R ;
    L=height(root->left) ;
    R=height(root->right) ;
 
    return(L>R?(L+1):(R+1)) ;
}

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )