[InterviewBit] Vertical Sum of a Binary Tree

Vertical Sum of a Binary Tree

  • Time :
  • Space :
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
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
void dfs(TreeNode* node, unordered_map<int,int>& mp, int v) {
if(!node) return;
mp[v] += node->val;
dfs(node->left, mp, v - 1);
dfs(node->right, mp, v + 1);
}
vector<int> Solution::verticalSum(TreeNode* A) {
unordered_map<int, int> mp;
dfs(A,mp,0);
vector<pair<int, int>> S;
for(auto [k,v] : mp) S.push_back({k,v});
sort(begin(S), end(S));
vector<int> res;
for(auto [_,v] : S) res.push_back(v);
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/11/10/PS/interviewbit/vertical-sum-of-a-binary-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.