/*
不能这样算 1
2 3
4
假设这样的tree target 是6
用下面的算法 2-4 这个组合会被算两变
应该用的方法: 写一个方法 只算每次剪掉root.val的值,另外再把没剪掉的重新递归; 看下面的code;
class Solution {
public int pathSum(TreeNode root, int sum) {
if(root == null) return 0;
int count = 0;
if(sum == root.val) count++;
int leftWithRoot = pathSum(root.left, sum - root.val);
int rightWithRoot = pathSum(root.right, sum - root.val);
int leftWithoutRoot = pathSum(root.left, sum);
int rightWithoutRoot = pathSum(root.right, sum);
return leftWithRoot + rightWithRoot + leftWithoutRoot + rightWithoutRoot + count;
}
}
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int pathSum(TreeNode root, int sum) {
if(root == null) return 0;
return helper(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum);
}
public int helper(TreeNode root, int sum) {
if(root == null) return 0;
//防止一条路径上有一个以上的路径可以得到相同的sum;
int count = 0;
if(root.val == sum) count++;
return helper(root.left, sum - root.val) + helper(root.right, sum - root.val) + count;
}
}