思路:此题思路为递归实现,递归思路为:在每层递归的过程中将各个节点的数据记录下来,不断将减少目标数据的值准备进行判断,当进行到叶子节点时要进行判断
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool hasPathSum(struct TreeNode* root, int targetSum) {
if(root==NULL)
{
return false;
}
int sum=root->val;
if(root->left==NULL&&root->right==NULL)
{
return targetSum==sum;
}
return hasPathSum(root->left,targetSum-sum)||hasPathSum(root->right,targetSum-sum);
}