437.路径总和III

437.路径总和III_第1张图片
437.路径总和III_第2张图片
437.路径总和III_第3张图片

法一:深度优先遍历,递归

  • rootSum(p,val)计算节点p向下且路径和为val的路径和
  • rootSum(p,val)=rootSum(p->left,val-pval)+rootSum(p->right,val-pval)
  • 遍历二叉树所有节点的rootSum并求和
class Solution {
public:
    int rootSum(TreeNode* node,long target){
        if(!node){
            return 0;
        }
        int ret=0;
        int val=node->val;
        if(val==target){
            ++ret;
        }
        ret+=rootSum(node->left,target-val);
        ret+=rootSum(node->right,target-val);
        return ret;
    }

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

法二:前缀和+深度优先遍历

  • 根节点root到node的前缀和sum
  • 已保存的前缀和中查找是否存在curr-target
class Solution {
public:
    unordered_map<long long,int>prefix;

    int dfs(TreeNode* node,long long sum,int target){
        if(!node) return 0;

        int ret=0;
        sum+=node->val;
        if(prefix.count(sum-target)){
            ret=prefix[sum-target];
        }

        ++prefix[sum];
        ret+=dfs(node->left,sum,target);
        ret+=dfs(node->right,sum,target);
        --prefix[sum];

        return ret;
    }
    int pathSum(TreeNode* root, int targetSum) {
        prefix[0]=1;
        return dfs(root,0,targetSum);
    }    
};

你可能感兴趣的:(力扣,深度优先,算法)