• + 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<<" ";
        }