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
|
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; } };
|