Created
August 10, 2020 17:32
-
-
Save SuryaPratapK/d73b9a97c2c8a2af762af106b794ad2d to your computer and use it in GitHub Desktop.
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
/** | |
* Definition for a binary tree node. | |
* struct TreeNode { | |
* int val; | |
* TreeNode *left; | |
* TreeNode *right; | |
* TreeNode() : val(0), left(nullptr), right(nullptr) {} | |
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} | |
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} | |
* }; | |
*/ | |
//BFS-Method | |
class Solution { | |
public: | |
vector<vector<int>> verticalTraversal(TreeNode* root) { | |
TreeNode *curr; | |
queue<pair<TreeNode*, int>> q; | |
q.push({root,0}); | |
vector<vector<int>> ans; | |
map<int,vector<int>> mymap; | |
//BFS | |
while(!q.empty()) | |
{ | |
int size = q.size(); | |
map<int,set<int>> mapset; | |
while(size--) | |
{ | |
curr = q.front().first; | |
int col = q.front().second; | |
q.pop(); | |
mapset[col].insert(curr->val); | |
if(curr->left) | |
q.push({curr->left,col-1}); | |
if(curr->right) | |
q.push({curr->right,col+1}); | |
} | |
for(auto it: mapset) | |
for(auto it2: it.second) | |
mymap[it.first].push_back(it2); | |
} | |
//Now pass all values from mymap to ans array | |
for(auto it: mymap) | |
ans.push_back(it.second); | |
return ans; | |
} | |
}; | |
//DFS Method | |
class Solution { | |
map<int,map<int,set<int>>> mymap; | |
void solve(TreeNode *curr,int col,int row) | |
{ | |
if(!curr) | |
return; | |
mymap[col][row].insert(curr->val); | |
solve(curr->left,col-1,row+1); | |
solve(curr->right,col+1,row+1); | |
} | |
public: | |
vector<vector<int>> verticalTraversal(TreeNode* root) { | |
solve(root,0,0); | |
vector<vector<int>> ans; | |
for(auto m1: mymap) | |
{ | |
ans.push_back(vector<int>()); | |
for(auto m2: m1.second) | |
{ | |
for(auto m3: m2.second) | |
ans.back().push_back(m3); | |
} | |
} | |
return ans; | |
} | |
}; |
Both the codes are giving error for this test case in leetcode
[3,1,4,0,2,2]
gives output = [[0],[1],[3,2],[4]]
expected output = [[0],[1],[3,2,2],[4]]
https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/submissions/
Use multiset instead of set
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use unordered_map<int, unordered_map<int, multiset>> mymap; instead of map<int,map<int,set>> mymap
as unordered map will be faster.