其他分享
首页 > 其他分享> > # 437. 路径总和 III【dfs+前缀和】

# 437. 路径总和 III【dfs+前缀和】

作者:互联网

文章目录

437. 路径总和 III【dfs+前缀和】

给定一个二叉树的根节点 root ,和一个整数 targetSum ,求该二叉树里节点值之和等于 targetSum 的 路径 的数目。

路径 不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点)。

示例 1:

输入:root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8
输出:3
解释:和等于 8 的路径有 3 条,如图所示。
示例 2:

输入:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
输出:3

提示:

二叉树的节点个数的范围是 [0,1000]
-109 <= Node.val <= 109
-1000 <= targetSum <= 1000

递归

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    private int pathSumIn(TreeNode root,int targetSum){
        int ans=0;
        if(root==null)return ans;
        if(targetSum==root.val)ans++;
        ans+=pathSumIn(root.left,targetSum-root.val)+pathSumIn(root.right,targetSum-root.val);
        return ans;
    }

    public int pathSum(TreeNode root, int targetSum) {
        int ans=0;
        if(root==null)return 0;
        ans=pathSum(root.left,targetSum)+pathSum(root.right,targetSum);
        
        if(targetSum==root.val)ans++;
        ans+=pathSumIn(root.left,targetSum-root.val)+pathSumIn(root.right,targetSum-root.val);
        //System.out.println(root.val+" "+res);
        return ans;
    }
}

时间复杂度O(n^2)
空间复杂度O(n)

前缀和

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    private HashMap<Integer,Integer> map= new HashMap<>();
    private int ans=0;

    private void dfs(TreeNode root, int targetSum,int cur){
        if(root==null)return;
        cur+=root.val;
        ans+=map.getOrDefault(cur-targetSum,0);
        //System.out.println(cur+" "+map.getOrDefault(cur-targetSum,0));
        map.put(cur,map.getOrDefault(cur,0)+1);
        dfs(root.left,targetSum,cur);
        dfs(root.right,targetSum,cur);
        map.put(cur,map.getOrDefault(cur,0)-1);
    }

    public int pathSum(TreeNode root, int targetSum) {
        if(root==null)return 0;
        
        map.put(0,1);
        dfs(root,targetSum,0);
        return ans;
    }
}

求什么之和的应该都想一下前缀和,而且从根到本节点只有一个和
时间复杂度O(n)
空间复杂度O(n)
注意开始前插入(0,1)

标签:TreeNode,val,int,root,dfs,targetSum,ans,437,III
来源: https://blog.csdn.net/Wuuuuuu2019/article/details/120553692