forked from fanfank/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpath-sum.cpp
37 lines (36 loc) · 944 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
/**
* 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 hasPathSum(TreeNode *root, int sum) {
// Note: The Solution object is instantiated only once and is reused by each test case.
return pathSum(root, 0, sum);
}
private:
bool pathSum(TreeNode *root, int sum, const int ans) {
if(root == NULL)
return false;
sum += root->val;
bool isLeaf = true;
if(root->left) {
isLeaf = false;
if(pathSum(root->left, sum, ans))
return true;
}
if(root->right) {
isLeaf = false;
if(pathSum(root->right, sum, ans))
return true;
}
if(isLeaf && sum == ans)
return true;
return false;
}
};