You are viewing a single comment's thread. Return to all comments →
C++ using Breadth-First Search (more at https://github.com/IhorVodko/Hackerrank_solutions , feel free to give a star :) )
void topView(Node * _root){ using namespace std; assert(_root); auto nodes = queue<pair<Node *, int>>(); auto widthToData = map<int, int>(); nodes.emplace(_root, 0); widthToData.insert({0, _root->data}); auto node = nodes.front().first; auto width = nodes.front().second; while(!nodes.empty()){ node = nodes.front().first; width = nodes.front().second; nodes.pop(); if(node->left){ nodes.emplace(node->left, width - 1); } if(node->right){ nodes.emplace(node->right, width + 1); } widthToData.insert({width, node->data}); } for(auto x : widthToData){ std::cout << x.second << " "; } }
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++ using Breadth-First Search (more at https://github.com/IhorVodko/Hackerrank_solutions , feel free to give a star :) )