/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool hasPathSum(TreeNode* root, int targetSum) {
if(root==NULL)//在示例三中这种情况直接false,后续不可能再执行这个条件的语句,因为在判断为叶子结点的时候递归已经停止
return false;
else{
if(root->left==NULL&&root->right==NULL)
if(targetSum-root->val==0)
return true;
else
return false;
else
return hasPathSum(root->left,targetSum-root->val)||hasPathSum(root->right,targetSum-root->val);
}
}
};
leecode112.路径总和
最新推荐文章于 2025-04-02 18:35:19 发布