-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPath Sum.cpp
More file actions
51 lines (40 loc) · 1.4 KB
/
Path Sum.cpp
File metadata and controls
51 lines (40 loc) · 1.4 KB
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
44
45
46
47
48
49
50
51
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void calculateNext(TreeNode* node, int tempS, int sum, bool &result)
{
if(node->left == NULL && node->right == NULL && tempS == sum)
{
result = true;
return;
}
if(node->left != NULL)
calculateNext(node->left, tempS+node->left->val, sum, result);
if(result == false && node->right!=NULL)
calculateNext(node->right, tempS+node->right->val, sum, result);
}
bool hasPathSum(TreeNode *root, int sum) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
bool result = false;
if(root == NULL)
return false;
int tempS = 0;
tempS = root->val;
if(root->left == NULL && root->right == NULL && tempS == sum)
result = true;
if(!result && root->left != NULL)
calculateNext(root->left, tempS+root->left->val, sum, result);
if(result == false && root->right!=NULL)
calculateNext(root->right, tempS+root->right->val, sum, result);
return result;
}
};