当前位置:网站首页>力扣------路径总和 III

力扣------路径总和 III

2022-07-06 21:00:00 qq_37760746

在这里插入图片描述

/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */
int count;
void sum(struct TreeNode* root, int targetSum,long int nowsum){
    
    if(nowsum==targetSum){
    
        count++;
    }
    if(root->left){
    
        nowsum=nowsum+root->left->val;
        sum(root->left,targetSum,nowsum);
        nowsum=nowsum-root->left->val;
    }
    if(root->right){
    
        nowsum=nowsum+root->right->val;
        sum(root->right,targetSum,nowsum);
        nowsum=nowsum-root->right->val;       
    }
}
void dfs(struct TreeNode* root, int targetSum){
    
    long int nowsum=0;
    nowsum=nowsum+root->val;
    sum(root, targetSum,nowsum);
    if(root->left){
    
        dfs(root->left,targetSum);
    }
    if(root->right){
    
        dfs(root->right,targetSum);
    }
}
int pathSum(struct TreeNode* root, int targetSum){
    
    count=0;
    if(!root){
    
        return count;
    }
    dfs(root,targetSum);
    return count;
}
原网站

版权声明
本文为[qq_37760746]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_37760746/article/details/125633926