You are viewing a single comment's thread. Return to all comments →
Actually there's no need to keep track of depth or to use another function, here's an example solution:
void topView(Node * root) { queue<pair<int,Node*>> q; q.push(make_pair(0,root)); map<int,Node*> ans; for(auto i=q.front();!q.empty();q.pop(),i=q.front()){ if(!i.second) continue; ans.insert(i); q.push(make_pair(i.first+1,i.second->right)); q.push(make_pair(i.first-1,i.second->left)); } for(auto i:ans) cout<<i.second->data<<" "; }
Seems like cookies are disabled on this browser, please enable them to open this website
Tree : Top View
You are viewing a single comment's thread. Return to all comments →
Under 10 lines of code C++ solution
Actually there's no need to keep track of depth or to use another function, here's an example solution: