Untitled
unknown
plain_text
a month ago
1.3 kB
2
Indexable
Never
class Solution { public: //Function to return a list of nodes visible from the top view //from left to right in Binary Tree. vector<int> topView(Node *root){ //Your code here if(root == nullptr) return {}; queue<pair<Node*, int>>q; // node line map<int,int> mp; // line node q.push( {root, 0} ); while(!q.empty()){ int sz = q.size(); while(sz--){ pair<Node*, int> curr = q.front(); q.pop(); int currNode = curr.first->data; int verticalLvl = curr.second; if(mp.find(verticalLvl) == mp.end()){ mp[verticalLvl] = currNode; } if(curr.first->left != nullptr){ q.push( {curr.first->left, verticalLvl-1 } ); } if(curr.first->right != nullptr){ q.push( {curr.first->right, verticalLvl+1 } ); } } } vector<int>ans; for(auto &curr : mp){ ans.push_back(curr.second); } return ans; } };
Leave a Comment