-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathLeetcode_path-sum.cc
61 lines (57 loc) · 1.26 KB
/
Leetcode_path-sum.cc
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
//http://oj.leetcode.com/problems/path-sum/
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
bool dfs(TreeNode*p, int value)
{
if(p->val == value && !(p->left) && !(p->right))
{
return true;
}
else if(p->left && dfs(p->left, value - p->val))
{
return true;
}
else if(p->right && dfs(p->right, value - p->val))
{
return true;
}
return false;
}
class Solution {
public:
bool hasPathSum(TreeNode *root, int sum) {
if(!root)
return false;
return dfs(root, sum);
}
};
//SECOND TRIAL
class Solution {
private:
bool dfs(TreeNode* root, int left)
{
if(left-root->val == 0 && !root->left && !root->right)
return true;
else
{
if(root->left && dfs(root->left, left-root->val))
return true;
if(root->right && dfs(root->right, left-root->val))
return true;
return false;
}
}
public:
bool hasPathSum(TreeNode *root, int sum) {
if(!root)
return false;
return dfs(root, sum);
}
};