/** * 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 { public: unordered_map<int,int> in_map; int res = 0; int pathSum(TreeNode* root, int targetSum) { if(root==NULL) return 0; in_map[0] = 1; // 前缀和为0的路径只有一条:哪个节点都不选 这个必须加上 presum(root, 0 , targetSum); return res; } void presum(TreeNode* root, int cursum, int targetSum){ if(root==NULL) return; cursum = cursum + root->val; if(in_map.find(cursum-targetSum)!=in_map.end()){ res = res + in_map[cursum-targetSum]; // 当前路径中存在以当前节点为终点的和为sum的子路径 } in_map[cursum]++; // 将当前节点加入路径 presum(root->left, cursum, targetSum); presum(root->right, cursum, targetSum); in_map[cursum]--; // 回溯 } };