Print Nodes in Top View of Binary Tree

PROBLEM :

You are given a pointer to the root of a binary tree. Print the top view of the binary tree.
You only have to complete the function.

For example :

     3
   /   \
  5     2
 / \   / \
1   4 6   7
 \       /
  9     8
Top View : 1 -> 5 -> 3 -> 2 -> 7
Input Format

You are given a function,
void top_view(node * root)
{

}

Output Format
Print the values on a single line separated by space.

Sample Input

     3
   /   \
  5     2
 / \   / \
1   4 6   7
 \       /
  9     8
 
Sample Output
1 5 3 2 7

Explanation

     3
   /   \
  5     2
 / \   / \
1   4 6   7
 \       /
  9     8
From the top only nodes 1,5,3,2 and 7 will be visible.

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

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

*/

void find_Min_Max(node *, int *,int *,int ) ;
void print_top(node *,int ,bool *,int ) ;
void top_view(node * root)
{
    if(root==NULL)
         return ;
    bool state=true ;
    int min,max,i ;
    min=0 ;
    max=0 ;
   
    find_Min_Max(root,&min,&max,0) ;
   
    for(i=min;i<=max;i++)
    {
        print_top(root,i,&state,0) ;
        state=true ;
    }
}

void find_Min_Max(node *root, int *min,int *max,int curr)
{
    if(root==NULL)
          return ;
   
    if(curr>(*max))
        (*max)=curr ;
    if(curr<(*min))
        (*min)=curr ;
   
    find_Min_Max(root->left,&(*min),&(*max),curr-1) ;
    find_Min_Max(root->right,&(*min),&(*max),curr+1) ;
}

void print_top(node *root,int dest,bool *state,int curr)
{
    if(root==NULL)
        return ;
   
    if((*state)!=true)
            return ;
   
    if(curr==dest&&(*state)==true)
    {
        cout<<root->data<<" " ;
        (*state)=false ;
    }
    if((*state)!=true)
            return ;
   
    if(dest<0)
    {
        print_top(root->left,dest,&(*state),curr-1) ;
        print_top(root->right,dest,&(*state),curr+1) ;  
    }
    else
    {
        print_top(root->right,dest,&(*state),curr+1) ;
        print_top(root->left,dest,&(*state),curr-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 )