the approach is similar to vertical order traverval
where in map
key–>
horizontal distance
value–>pair<int,int> (root->data,level}
so we have update the map when we see new horizontal distance or when the level of the current node is less than the level seen for sofar in the map for the same horizontal distance right?
void topView1(node *root, int level, int dist, map<int, pair<int, int> > &mp) {
if(root == NULL) {
return;
}
if(mp.find(dist) == mp.end() or level<mp[dist].second) {//this should be like this level>mp[dist].second right?
mp[dist] = {root->data, level};
}
topView1(root->left, level+1, dist-1, mp);
topView1(root->right, level+1, dist+1, mp);
}
void topView(node *root)
{
map<int, pair<int, int> >mp;
topView1(root, 0, 0, mp);
for(auto val:mp){
cout<<val.second.first<<" ";
}