-
Notifications
You must be signed in to change notification settings - Fork 24
/
112-Path_Sum.cpp
33 lines (33 loc) · 886 Bytes
/
112-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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool has_sum(int sum, TreeNode* root)
{
if(root->left !=NULL && root->right!=NULL)
return (has_sum(sum-(root->val),root->left) || has_sum(sum-(root->val),root->right));
else if(root->left!=NULL)
return has_sum(sum-(root->val),root->left);
else if(root->right!=NULL)
return has_sum(sum-(root->val),root->right);
else
{
sum-=(root->val);
if(sum==0)
return true;
return false;
}
}
bool hasPathSum(TreeNode* root, int sum) {
if(root!=NULL)
return has_sum(sum,root);
return false;
}
};