Vertical Sum of a Binary Tree
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
|
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; }
|