一开始有好多细节没有注意到,但结果还是好的
class Solution {
public:
int res = 0;
bool hasPathSum(TreeNode* root, int targetSum) {
return judge(root,targetSum,res);
}
bool judge(TreeNode* root,int targetSum,int res){
if(root == NULL){
return false;
}
if(root->left == NULL){
if(root->right == NULL && res + root->val == targetSum)
return true;
else
return judge(root->right,targetSum,res+root->val);
}
if(root->right == NULL){
return judge(root->left,targetSum,res + root->val);
}
res += root->val;
return judge(root->left,targetSum,res)||judge(root->right,targetSum,res);
}
};