You are viewing a single comment's thread. Return to all comments →
C++ solution :
void topView(Node* root) { if (!root) return; map<Node*, int> hd; map<int, int> m; deque<Node*> q; q.push_back(root); hd[root]=0; m[hd[root]]=root->data; while(!q.empty()) { if (root->left) { hd[root->left] = hd[root]-1; if (!m[hd[root->left]]) m[hd[root->left]] = root->left->data; q.push_back(root->left); } if (root->right) { hd[root->right] = hd[root]+1; if (!m[hd[root->right]]) m[hd[root->right]] = root->right->data; q.push_back(root->right); } q.pop_front(); if (q.size()) root = q.front(); } map<int, int>::iterator it = m.begin(); while(it!=m.end()) { cout << it->second << " "; it++; } }
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 →
C++ solution :