思路:递归。判断每个节点是不是叶子节点,是的话左右节点为空,不是的话用sum减去该节点的值,并继续调用左右节点,sum
/**
* 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) {
if(root==NULL){
return false;
}
sum-=root->val;
if(root->left==NULL&&root->right==NULL){
return sum==0;
}
else{
return hasPathSum(root->left,sum)||hasPathSum(root->right,sum);
}
}
};