• + 6 comments

    This is the actual code for top view of a tree :

    typedef pair<int,int> v_h; 
    map <int,v_h> m; // map
    map <int, v_h> :: iterator itr; //itterator
    
    void store_view(node * root,int i,int h)
        {
        if(root==NULL)
            return;
        itr=m.find(i);
        if(itr==m.end())
            m[i]=make_pair(h,root->data);
        else
        {
            if(itr->second.first > h)
                m[i]=make_pair(h,root->data);
        }
        if(root->left!=NULL)
            store_view(root->left,i-1,h+1);
        if(root->right!=NULL)
            store_view(root->right,i+1,h+1);
         
    }
    
    void print_map()
        {
        for(itr = m.begin(); itr != m.end(); ++itr)
            cout<<itr->second.second<<" ";
    }
    
    void topView(node * root)
    {
       store_view(root,0,0);
       print_map();
        return;
    }
    

    but the problem demands the top view according to the root node only :

    void for_left(node * root)
    {
        if(root->left!=NULL)
            for_left(root->left);
        cout<<root->data<<" ";
    }
    
    
    void for_right(node * root)
    {
        cout<<root->data<<" ";
        if(root->right!=NULL)
            for_right(root->right);
    }
    
    void topView(node * root)
    {
        if(root->left!=NULL)
            for_left(root->left);
        cout<<root->data<<" ";
        if(root->right!=NULL)
            for_right(root->right);
        
    }