two flavors:
//first
class Solution {
public:
bool hasPathSum(TreeNode *root, int sum) {
if(root==NULL)
return false;
if(root->left==NULL && root->right==NULL && root->val==sum)
return true;
return hasPathSum(root->left, sum-root->val)||hasPathSum(root->right,sum-root->val);
}
};
//second
class Solution {
public:
bool hasPathSum(TreeNode *root, int sum) {
int cur=0;
return help(root,cur,sum);
}
bool help(TreeNode*root, int &cur,int sum ){
if(!root) return false;
cur+=root->val;
if(root->left==NULL&&root->right==NULL&& cur==sum)
return true;
if(root->left&&help(root->left,cur,sum))
return true;
if(root->right&&help(root->right,cur,sum))
return true;
cur-=root->val;
return false;
}
};
No comments:
Post a Comment