forked from iphkwan/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Path_Sum.cc
36 lines (36 loc) · 932 Bytes
/
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
/**
* 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 *root, int total) {
total -= root->val;
if (root->left == NULL && root->right == NULL) {
if (total == 0) {
return true;
}
return false;
}
if (root->left && dfs(root->left, total)) {
return true;
}
if (root->right && dfs(root->right, total)) {
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);
}
};