文章

99

粉丝

120

获赞

8

访问

110.0k

头像
路径总和 III 437
备考心情
发布于2024年9月4日 19:43
阅读数 1.2k

/**
 * 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:
    int dfs(TreeNode* u, int target){
        if(!u)return 0;
        int res = 0;
        if(u->val==target)res++;
        res += dfs(u->left,target-u->val);
        res += dfs(u->right,target-u->val);
        return res;
    }
    int pathSum(TreeNode* root, int targetSum) {
        //暴力,从每个点开始搜.
        if(!root)return 0;
        int res = dfs(root,targetSum);
        res += pathSum(root->left,targetSum);
        res += pathSum(root->right,targetSum);
        return res;
    }
};

 

登录查看完整内容


登录后发布评论

暂无评论,来抢沙发