437. Path Sum III

problem

solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
long traverse(TreeNode * root, long targetSum){

if(!root) return 0;

targetSum -= root->val;
inlongt ret = 0;
if(targetSum==0) ret++;
ret+=traverse(root->left, targetSum)+traverse(root->right, targetSum);
return ret;
}
int pathSum(TreeNode* root, int targetSum) {

if(!root ) return 0;
// 路徑包含當下的節點
long ret = traverse(root, targetSum);

ret += pathSum(root->left, targetSum);
ret += pathSum(root->right, targetSum);
return ret;

}
};