Skip to content

Commit

Permalink
Merge pull request #128 from Saurabh0625/master
Browse files Browse the repository at this point in the history
Create top_view
  • Loading branch information
Ayushsinhahaha authored Oct 28, 2022
2 parents 0d24ec5 + a7ca354 commit f5c1fa1
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
35 changes: 35 additions & 0 deletions top_view
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;
}

};
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 f5c1fa1

Please sign in to comment.