Ticker

6/recent/ticker-posts

Header Ads Widget

Responsive Advertisement

Right View of Binary Tree || 2 approach



 /**
    vector rightView(Node *root)
    {
       vectorans;
       solve(root,ans);
       return ans;
    }
    void solve (Node*root,vector&ans)
    {
        queuevt;
        vt.push(root);
        vt.push(NULL);
        while(!vt.empty())
        {
            Node* temp=vt.front();
            vt.pop();
            if(temp!=NULL)
            {
                Node* nextTemp=vt.front();
                if(nextTemp==NULL)
                {
                    ans.push_back(temp->data);
                }
                if(temp->left)
                {
                   vt.push(temp->left);
                }
                if(temp->right)
                {
                    vt.push(temp->right);
                }
            }
            else
            {
                if(!vt.empty())
                {
                     vt.push(NULL);
                }
               
                
            }
        }
    }
    */
    
// Second Approach
 vector rightView(Node *root)
{
      
    if(root==NULL)
    {
      
        return {};
    }
    vectorans;
     queueqt;
        qt.push(root);
       while(!qt.empty())
       {
           int n=qt.size();
           for(int i=0;idata);
               }
               if(curr->left)
               {
                   qt.push(curr->left);
               }
               if(curr->right)
               {
                   qt.push(curr->right);
               }
           }
       }
       return ans;
}

Post a Comment

0 Comments