-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.cpp
More file actions
57 lines (47 loc) · 1.19 KB
/
Copy pathsolution.cpp
File metadata and controls
57 lines (47 loc) · 1.19 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/* Structure of binary tree node
class Node{
public:
int data;
Node* left, right;
Node(int item)
{
data = item;
left = nullptr;
right = nullptr;
}
}
*/
class Solution
{
public:
// DFS function to traverse the tree
void dfs(Node *root, int col, map<int, int> &mp)
{
// If node is null, simply return
if (root == nullptr)
return;
// Add current node value into its vertical column sum
mp[col] += root->data;
// Move left with column -1
dfs(root->left, col - 1, mp);
// Move right with column +1
dfs(root->right, col + 1, mp);
}
vector<int> verticalSum(Node *root)
{
// Map stores:
// key -> vertical column
// value -> sum of nodes in that column
map<int, int> mp;
// Start DFS from root at column 0
dfs(root, 0, mp);
vector<int> ans;
// Map automatically keeps keys sorted
// So values come from left-most to right-most
for (auto it : mp)
{
ans.push_back(it.second);
}
return ans;
}
};