int count;
void sum(struct TreeNode* root, int targetSum,long int nowsum){
if(nowsum==targetSum){
count++;
}
if(root->left){
nowsum=nowsum+root->left->val;
sum(root->left,targetSum,nowsum);
nowsum=nowsum-root->left->val;
}
if(root->right){
nowsum=nowsum+root->right->val;
sum(root->right,targetSum,nowsum);
nowsum=nowsum-root->right->val;
}
}
void dfs(struct TreeNode* root, int targetSum){
long int nowsum=0;
nowsum=nowsum+root->val;
sum(root, targetSum,nowsum);
if(root->left){
dfs(root->left,targetSum);
}
if(root->right){
dfs(root->right,targetSum);
}
}
int pathSum(struct TreeNode* root, int targetSum){
count=0;
if(!root){
return count;
}
dfs(root,targetSum);
return count;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43