Problem
You are given a binary tree in which each node contains an integer value (which might be positive or negative). Design an algorithm to count the number of paths that sum to a given value. The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).
Example
Given the following tree and sum = 22,
Output:
3
Explanation: Paths that have sum 22 are: [5,4,11,2], [5,8,4,5], [4,11,7]
Solution
注意:路径不必从树根开始,到叶节点结束。
2020-3-4 dfs递归,日后再看优化方法。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void dfs(TreeNode* root,int sum,int &curSum,int &pathNum)
{
if(!root)
return;
curSum += root->val;
if(curSum == sum)
{
++pathNum;
}
if(root->left)
dfs(root->left,sum,curSum,pathNum);
if(root->right)
dfs(root->right,sum,curSum,pathNum);
curSum -= root->val;
}
int pathSum(TreeNode* root, int sum) {
if(!root)
return 0;
int curSum = 0;
int pathNum = 0;
dfs(root,sum,curSum,pathNum);
pathNum += pathSum(root->left,sum);
pathNum += pathSum(root->right,sum);
return pathNum;
}
};