Leetcode 437. Path Sum III

https://leetcode.com/problems/path-sum-iii/

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
/**
* 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:
int pathSum(TreeNode* root, int sum) {
int res = 0;
if(!root){
return 0;
}
int temp = 0;
dfs(root, sum, res, temp);

res += pathSum(root->left, sum) + pathSum(root->right, sum);

return res;
}

void dfs(TreeNode * root, int & sum, int & res, int temp){
if(!root){
return;
}

temp += root->val;

if(temp == sum){
res++;
}

dfs(root->left, sum, res, temp);
dfs(root->right, sum, res, temp);
}
};
0%