Skip to content

Commit

Permalink
Create top_view1
Browse files Browse the repository at this point in the history
  • Loading branch information
Saurabh0625 authored Oct 28, 2022
1 parent c0c1467 commit a7ca354
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions top_view1
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
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)
{
vector<int> ans;
if(root == NULL) return ans;
map<int,int> mpp;
queue<pair<Node*, int>> q;
q.push({root, 0});
while(!q.empty()) {
auto it = q.front();
q.pop();
Node* node = it.first;
int line = it.second;
if(mpp.find(line) == mpp.end()) mpp[line] = node->data;

if(node->left != NULL) {
q.push({node->left, line-1});
}
if(node->right != NULL) {
q.push({node->right, line + 1});
}

}

for(auto it : mpp) {
ans.push_back(it.second);
}
return ans;
}

};

0 comments on commit a7ca354

Please sign in to comment.