leetcode-每日一题2021.9.28 路径总和 III

题目

力扣

思路一 深度优先搜索

算出以每个节点为根节点有子树的值加起来是targetSum的情况。rootSum(p,val) 表示以节点 p 为起点向下且满足路径总和为 val的路径数目。

代码一

/**
 * 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 rootSum(TreeNode* root,int targetSum){
        if(!root)
            return 0;

        int ret=0;
        if(root->val==targetSum)
            ret++;

        ret+=rootSum(root->left,targetSum-root->val);
        ret+=rootSum(root->right,targetSum-root->val);
        return ret;
    }
    int pathSum(TreeNode* root, int targetSum) {
        if(!root)
            return 0;
        int ret=rootSum(root,targetSum);
        ret+=pathSum(root->left,targetSum);
        ret+=pathSum(root->right,targetSum);
        return ret;
    }
};

思路二 前缀和

遍历结点,计算从根节点到该结点的前缀和,并存储下来,如果这个前缀和正好等于targetSum与某个结点的前缀和之和,那么路径数目就加1。

代码二

/**
 * 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:
    unordered_map<long long,int> prefix;
    int dfs(TreeNode* root,long long curr,int targetSum){
        if(!root)
            return 0;
        int ret=0;
        curr+=root->val;
        if(prefix.count(curr-targetSum))
            ret=prefix[curr-targetSum];
        prefix[curr]++;
        ret+=dfs(root->left,curr,targetSum);
        ret+=dfs(root->right,curr,targetSum);
        prefix[curr]--;
        return ret;
    }
    int pathSum(TreeNode* root, int targetSum) {
        prefix[0]=1;
        return dfs(root,0,targetSum);
    }
};
上一篇:js中如何在不影响既有事件监听的前提下新增监听器


下一篇:xml中有空值节点,导入到数据库null值