[LeetCode] Path Sum III

437. Path Sum III

Given the root of a binary tree and an integer targetSum, return the number of paths where the sum of the values along the path equals targetSum.

The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).

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
/**
* 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 {
pair<int, unordered_map<int, int>> solution(TreeNode* node, int t) {
if(!node) return {0, {}};
unordered_map<int, int> m {{node->val, 1}};
auto [lres, lm] = solution(node->left, t);
auto [rres, rm] = solution(node->right, t);
for(auto& [k, v]: lm) m[k + node->val] += v;
for(auto& [k, v]: rm) m[k + node->val] += v;
return {lres + rres + m[t], m};
}
public:
int pathSum(TreeNode* root, int targetSum) {
auto [res, _] = solution(root, targetSum);
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/09/PS/LeetCode/path-sum-iii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.