-
Notifications
You must be signed in to change notification settings - Fork 0
/
Gfg_Vertical_sum.cpp
45 lines (37 loc) · 1.14 KB
/
Gfg_Vertical_sum.cpp
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
42
43
44
45
class Solution{
public:
vector <int> verticalSum(Node *root) {
map<int,map<int,vector<int>>> nodes;
queue<pair<Node*,pair<int,int>>>q;
vector<int> ans;
if(root==NULL){
return ans;
}
int sum;
q.push(make_pair(root,make_pair(0,0)));
while(!q.empty()){
pair<Node*,pair<int,int>>temp=q.front();
q.pop();
Node*frontnode=temp.first;
int hd=temp.second.first;
int lvl=temp.second.second;
nodes[hd][lvl].push_back(frontnode->data);
if(frontnode->left){
q.push(make_pair(frontnode->left,make_pair(hd-1,lvl+1)));
}
if(frontnode->right){
q.push(make_pair(frontnode->right,make_pair(hd+1,lvl+1)));
}
}
for(auto i:nodes){
sum=0;
for(auto j:i.second){
for(auto k:j.second){
sum+=k;
}
}
ans.push_back(sum);
}
return ans;
}
};