/**************************************************************************
*
* 437. [Path Sum III](https://leetcode.com/problems/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).
*
* Example:
* root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8
* 10
* / \
* 5 -3
* / \ \
* 3 2 11
* / \ \
* 3 -2 1
*
* Return 3. The paths that sum to 8 are:
* 1. 5 -> 3
* 2. 5 -> 2 -> 1
* 3. -3 -> 11
*
**************************************************************************/
class Solution {
public:
int pathSum(TreeNode* root, int sum) {
if (root == nullptr)return 0;
//假设包含当前节点
int res = findPath(root, sum);
//不包含当前节点的值,转到左右自树中寻找
res += pathSum(root->left, sum);
res += pathSum(root->right, sum);
return res;
}
private:
int findPath(TreeNode *node, int sum) {
if (node == nullptr)return 0;
int res = 0;
if (node->val == sum)
res += 1;
//如果相加得到sum后 还要继续往下 因为有负数 加加减减之后可能重新得sum
res += findPath(node->left, sum - node->val);
res += findPath(node->right, sum - node->val);
return res;
}
};