递归
class Solution {
public:
bool hasPathSum(TreeNode* root, int targetSum) {
if(root==NULL)return false;
sum +=root->val;
if(!root->left&&!root->right)
{
if(sum==targetSum)return true;
else return false;
}
if(root->left)
if(hasPathSum(root->left,targetSum))return true;
//回溯
else sum -=root->left->val;
if(root->right)
if(hasPathSum(root->right,targetSum))return true;
else sum -=root->right->val;
return false;
}
int sum = 0;
};
class Solution {
public:
bool dfs(TreeNode* Node,int count)
{
if(!Node->left && !Node->right)
{
if(count==0)return true;
else return false;
}
if(Node->left)
if(dfs(Node->left,count-Node->left->val))return true;
if(Node->right)
if(dfs(Node->right,count-Node->right->val))return true;
return false;
}
bool hasPathSum(TreeNode* root, int targetSum) {
if(root==NULL)return false;
return dfs( root,targetSum-root->val);
}
};