Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save SuryaPratapK/d73b9a97c2c8a2af762af106b794ad2d to your computer and use it in GitHub Desktop.
Save SuryaPratapK/d73b9a97c2c8a2af762af106b794ad2d to your computer and use it in GitHub Desktop.
/**
* 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;
}
};
@Ankush-0694
Copy link

how we can store 2-d vector in main function after return and print the values from the main-vector.

@mandepsingh
Copy link

@ankush the 2-d vector you talking about is global variable.

@Kamlesh480
Copy link

Kamlesh480 commented Apr 10, 2021

Use map<int,map<int,multiset<int>>> mymap; instead of map<int,map<int,set<int>>> mymap
In case of set it will give an error because set cannot have duplicate values.

@shashankrustagi
Copy link

Use unordered_map<int, unordered_map<int, multiset>> mymap; instead of map<int,map<int,set>> mymap
as unordered map will be faster.

@PRASANNA-416
Copy link

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/

@Ayushbikki
Copy link

Use multiset instead of set

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment