Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example:Given the below binary tree and
sum = 22
,
5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2
which sum is 22.
#include<iostream>
using namespace std;
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,int theNumber){
if(root==NULL)
return theNumber==sum;
if(root->left==NULL && root->right==NULL)
return theNumber==sum+root->val;
sum+=root->val;
return (hasPathSum(root->left,sum,theNumber) || hasPathSum(root->right,sum,theNumber));
}
bool hasPathSum_version2(TreeNode *root,int sum){
if(root==NULL)
return false;
if(root->left==NULL && root->right==NULL)
return sum==root->val;
return hasPathSum_version2(root->left,sum-(root->val)) || hasPathSum_version2(root->right,sum-(root->val));
}
};
int main() {
TreeNode a(5);
TreeNode b(4);
TreeNode c(8);
TreeNode d(11);
TreeNode e(13);
TreeNode f(4);
TreeNode g(7);
TreeNode h(2);
TreeNode i(1);
a.left=&b;a.right=&c;
b.left=&d;b.right=NULL;
c.left=&e;c.right=&f;
d.left=&g;d.right=&h;
e.left=NULL;e.right=NULL;
f.left=NULL;f.right=&i;
g.left=NULL;g.right=NULL;
h.left=NULL;h.right=NULL;
i.left=NULL;i.right=NULL;
Solution sol;
// bool hehe=sol.hasPathSum_version2(&a,22);
bool hehe=sol.hasPathSum(&a,0,22);
cout<<hehe<<endl;
}