-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathPath-Sum.cpp
39 lines (37 loc) · 984 Bytes
/
Path-Sum.cpp
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
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
bool res = false;
if (root == NULL)
return res;
helper(root, sum, res);
return res;
}
void helper(TreeNode* root, int expectNumber, bool &res)
{
if (root == NULL)
return;
bool isLeaf = root->left == NULL && root->right == NULL;
if (expectNumber == root->val && isLeaf)
{
res = true;
}
helper(root->left, expectNumber-root->val, res);
helper(root->right, expectNumber-root->val, res);
}
};
// Solution 2:
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if (root==NULL)
return false;
sum -= root->val;
bool isLeaf = (root->left==NULL) && (root->right==NULL);
if (isLeaf)
{
return sum==0;
}
return hasPathSum(root->left, sum) || hasPathSum(root->right, sum);
}
};