forked from chetannihith/python-hacktoberfest25
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVerticalTrv.cpp
More file actions
41 lines (41 loc) · 1.23 KB
/
VerticalTrv.cpp
File metadata and controls
41 lines (41 loc) · 1.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/**
* 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, multiset<int>>> nodes;
queue<pair<TreeNode*, pair<int, int>>> todo;
todo.push({root, {0,0}});
while(!todo.empty()){
auto p = todo.front();
todo.pop();
TreeNode* node = p.first;
int x = p.second.first, y = p.second.second;
nodes[x][y].insert(node->val);
if(node -> left){
todo.push({node->left, {x-1, y+1}});
}
if(node->right){
todo.push({node->right, {x+1, y+1}});
}
}
vector<vector<int>> ans;
for(auto p : nodes){
vector<int> col;
for(auto q : p.second){
col.insert(col.end(), q.second.begin(), q.second.end());
}
ans.push_back(col);
}
return ans;
}
};