二叉树:路径总和,回溯有时候会藏起来

112. 路径总和

在这里插入图片描述

class Solution {
    
    
public:
    bool hasPathSum(TreeNode* root, int targetSum) {
    
    
        if(root == NULL)
        return false;

        if(!root->left && !root->right && targetSum == root->val)
        {
    
    
            return true;
        }
        return hasPathSum(root->left, targetSum - root->val) || hasPathSum(root->right, targetSum - root->val);
    }
};

回溯隐藏在targetSum - root->val,targetSum - root->val这里, 因为把targetSum - root->val直接作为参数传进去,函数结束,count的数值没有改变.

我们要把题目分析清楚之后,在追求代码精简

猜你喜欢

转载自blog.csdn.net/cckluv/article/details/112835984