原理:利用嵌套,让f(root,sum) = f(root->right,sum-root.val) || f(root->left,sum-root.val),最后到尾节点时候是否sum为0
/**
* Definition for a binary tree node.
* 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)
{
//cout<<sum<<root->val<<endl;
if(root == NULL)
{
return false;
}
sum = sum - root->val;
if(root->right == NULL && root->left == NULL)
{
//cout<<"here"<<endl;
return sum == 0;
}
else
{
return hasPathSum(root->right, sum) || hasPathSum(root->left, sum);
}
}
};