We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
  • HackerRank Home

    HackerRank

  • |
  • Prepare
  • Certify
  • Compete
  • Apply
  • Hiring developers?
  1. Prepare
  2. Data Structures
  3. Trees
  4. Tree : Top View
  5. Discussions

Tree : Top View

Problem
Submissions
Leaderboard
Discussions
Editorial

    You are viewing a single comment's thread. Return to all comments →

  • 2101640100219_cs
    3 months ago+ 0 comments

    Time Complexity :- O(n) ------ HashMap

    void topView(Node * root) {
            map<int,int>i;
            queue<pair<Node*,int>>q;q.push({root,500});
            while(!q.empty()){
                pair<Node*,int> t=q.front();q.pop();
                if(t.first->left)q.push({t.first->left,t.second-1});
                if(t.first->right)q.push({t.first->right,t.second+1});
                if(!i[t.second])i[t.second]=t.first->data;
            }
            for(auto k:i)cout<<k.second<<" ";
        }
    
    0|
    Permalink
  • Blog
  • Scoring
  • Environment
  • FAQ
  • About Us
  • Support
  • Careers
  • Terms Of Service
  • Privacy Policy