Tree: Level Order Traversal

PROBLEM :

ou are given a pointer to the root of a binary tree. You need to print the level order traversal of this tree. In level order traversal, we visit the nodes level by level from left to right.
You only have to complete the function.
For example:

         3
       /   \
      5     2
     / \    /
    1   4  6
For the above tree, the level order traversal is 3 -> 5 -> 2 -> 1 -> 4 -> 6.

Sample Input

         3
       /   \
      5     2
     / \    /
    1   4  6
Sample Output

3 5 2 1 4 6

Explanation

Level 1:        3
                    /   \
Level 2:     5     2
                  / \    /
Level 3:   1   4  6

We need to print the nodes level by level. We process each level from left to right.
Level Order Traversal: 3 -> 5 -> 2 -> 1 -> 4 -> 6

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


/*
struct node
{
    int data;
    node* left;
    node* right;
}*/


int height(node *) ;
void print_level(node *,int) ;

void LevelOrder(node * root)
{
    int h,i ;
   
    if(root==NULL)
        return ;
    h=height(root) ;
 
    for(i=0;i<=h;i++)
        print_level(root,i) ;
}

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

void print_level(node *root,int level)
    {
    if(root==NULL)
return ;
    if(level==0)
        cout<<root->data<<" " ;
    else
        {
        print_level(root->left,level-1) ;
        print_level(root->right,level-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 )