Reverse Level Order Traversal

PROBLEM :

Write a function to print Reverse Level Order Traversal of a tree. For below tree, function should print 4 5 2  3 1 .
                                             
 
                                     



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 reverse level order traversal of the tree.

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

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

/* A 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) ;

void reversePrint(struct node *root)
{
    if(root==NULL)
    return ;
    int h,i ;
    h=height(root) ;
   
    for(i=h;i>0;i--)
       print(root,i) ;
}

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

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 )