987. Vertical Order Traversal of a Binary Tree
/**
* 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) {}
* };
*/
class Solution {
public:
vector<vector<int> > verticalTraversal(TreeNode* root) {
map<int, map<int, set<int> > > M;
vector<vector<int> > V;
queue<pair<TreeNode*, pair<int, int> > > Q;
pair<TreeNode*, pair<int, int> > p;
if(root) Q.push({root, {0, 0}});
while(!Q.empty()) {
p = Q.front();
Q.pop();
M[p.second.first][p.second.second].insert(p.first->val);
if(p.first->left) Q.push({p.first->left, {p.second.first-1, p.second.second+1}});
if(p.first->right) Q.push({p.first->right, {p.second.first+1, p.second.second+1}});
}
for(auto &a : M) {
vector<int> tempV;
for(auto &it : a.second) {
tempV.insert(tempV.end(), it.second.begin(), it.second.end());
}
V.push_back(tempV);
}
return V;
}
};