这道题的一个测试例子是[]0->false。。。我觉得不太对啊,我总感觉这个应该输出true才对啊……不管了他说false就false吧,我的代码:
/**
* 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;
if(root->left == NULL && root->right == NULL)
{
if(root->val == sum)
return true;
else
return false;
}
else
return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val);
}
};
其中的一个else可以省略,让代码看起来更简单一点:
bool hasPathSum(TreeNode *root, int sum) {
if (root == NULL) return false;
if (root->val == sum && root->left == NULL && root->right == NULL) return true;
return hasPathSum(root->left, sum-root->val) || hasPathSum(root->right, sum-root->val);
}