-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPath Sum.cpp
More file actions
85 lines (81 loc) · 1.96 KB
/
Path Sum.cpp
File metadata and controls
85 lines (81 loc) · 1.96 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool DFS(TreeNode *now, int sum, int targetSum)
{
sum += now->val;
if(now->left == NULL && now->right == NULL)
{
if(sum == targetSum)
return true;
else
return false;
}
if(now->left != NULL)
{
if(DFS(now->left, sum, targetSum) == true)
return true;
}
if(now->right != NULL)
{
if(DFS(now->right, sum, targetSum) == true)
return true;
}
return false;
}
bool hasPathSum(TreeNode *root, int sum) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(root == NULL)
return false;
return DFS(root, 0, sum);
}
};
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool DFS(TreeNode *now, int sum)
{
if(now->left == NULL && now->right == NULL)
{
if(sum - now->val == 0)
return true;
else
return false;
}
if(now->left != NULL)
{
if(DFS(now->left, sum - now->val))
return true;
}
if(now->right != NULL)
{
if(DFS(now->right, sum - now->val))
return true;
}
return false;
}
bool hasPathSum(TreeNode *root, int sum) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(root == NULL)
return false;
return DFS(root, sum);
}
};