forked from moranzcw/LeetCode-NOTES
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.cpp
More file actions
30 lines (29 loc) · 698 Bytes
/
solution.cpp
File metadata and controls
30 lines (29 loc) · 698 Bytes
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
/**
* 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 dfs(TreeNode* root, int &sum, int tempSum)
{
if(!root)
return 0;
tempSum += root->val;
int flag = 0;
if(tempSum == sum)
flag = 1;
return flag + dfs(root->left,sum,tempSum) + dfs(root->right,sum,tempSum);
}
int pathSum(TreeNode* root, int sum)
{
if(!root)
return 0;
return dfs(root, sum, 0) + pathSum(root->left, sum) + pathSum(root->right, sum);
}
};