437. 路径总和 III

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/path-sum-iii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


一个思路是遍历每一个节点,以该节点为根节点,找路径。

  int count=0;
    public int pathSum(TreeNode root, int targetSum) {
        sum(root,targetSum);
        return count;
    }
    public void sum(TreeNode node, int targetSum) {
        if(node == null) {
            return;
        }
        dfs(node,targetSum);
        sum(node.left, targetSum);
        sum(node.right, targetSum);
    }

    public void dfs(TreeNode node, int targetSum) {
        if(node == null) {
            return;
        }
        if(node.val == targetSum) {
            count++;
        }
        dfs(node.left, targetSum-node.val);
        dfs(node.right, targetSum-node.val);
    }

还有一个中巧妙的方法,记录路径路径之和,如果路径和-目标和在缓存中有说明有从缓存的那个节点,到目前的节点有目标个的路径。

  private int ans = 0;
    public int pathSum(TreeNode root, int sum) {
        if(root == null) {
            return ans;
        }
        Map<Integer,Integer> map = new HashMap<>();
        map.put(0,1);
        dfs(root, sum, map, 0);
        return ans;

    }

    private void dfs(TreeNode root, int target, Map<Integer,Integer> map, int sum) {
        if(root == null) {
            return;
        }
        sum += root.val;
        if(map.get(sum-target) != null) {
            ans += map.get(sum-target);
        }
        if(map.get(sum) == null) {
            map.put(sum,1);
        } else {
            map.put(sum, map.get(sum) +1);
        }
        dfs(root.left, target, map, sum);
        dfs(root.right, target, map, sum);
        if(map.get(sum) == 1) {
            map.remove(sum);
        } else {
            map.put(sum, map.get(sum) - 1);
        }

    }
posted @ 2022-02-23 22:22  一颗青菜  阅读(4)  评论(0)    收藏  举报