# leetcode437. 路径总和 III !

Tree：10         sum = 8
/  \
5   -3
/ \    \
3   2   11
/ \   \
3  -2   1



#### 方法1. 双递归


int pathSum(TreeNode* root, int sum) {
if (root == NULL) return 0;
return   helper(root, sum) +
pathSum(root->left, sum) +
pathSum(root->right, sum);
}

int helper(TreeNode* root, int sum) {
if (root == NULL) return 0;
sum -= root->val;
int ans = (sum != 0)?0:1;
return ans + helper(root->left, sum) + helper(root->right, sum);
}


#### 方法2. DFS回溯+记忆化搜索

hash的key代表路径和，那么0->1 是天然存在的，就是说：还没有开始遍历，前缀和就是0

	public int pathSum(TreeNode root, int sum) {
Map<Integer, Integer> hashPathSum = new HashMap<>();
hashPathSum.put(0, 1);
return helper(root, hashPathSum, sum, 0);
}
int helper(TreeNode root, Map<Integer, Integer> hashPathSum, int sum, int pathSum) {
if (root == null) return 0;

pathSum += root.val;
int ans = hashPathSum.getOrDefault(pathSum - sum, 0);// 先判断，再put
hashPathSum.put(pathSum, hashPathSum.getOrDefault(pathSum, 0) + 1);

ans += helper(root.left, hashPathSum, sum, pathSum);
ans += helper(root.right, hashPathSum, sum, pathSum);

hashPathSum.put(pathSum, hashPathSum.get(pathSum) - 1); // 回溯,pathsum个数减1
return ans;
}


02-12 148

02-22 83

10-23 1万+

08-10 100

12-12 299

05-16 516

10-11 192

10-10 139

08-19 161

03-19 90

09-01 325

03-20 205

12-18 437

09-01 2760

10-27 620

04-10 79

06-10 68

06-27 85

01-04 157

#### 437. 路径总和 III

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客