-
Notifications
You must be signed in to change notification settings - Fork 52
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #128 from Saurabh0625/master
Create top_view
- Loading branch information
Showing
2 changed files
with
70 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
|
||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
|
||
}; |