Skip to content

Latest commit

 

History

History
executable file
·
80 lines (62 loc) · 1.84 KB

437.md

File metadata and controls

executable file
·
80 lines (62 loc) · 1.84 KB

题目描述

给定一个二叉树,它的每个结点都存放着一个整数值。

找出路径和等于给定数值的路径总数。

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

二叉树不超过1000个节点,且节点数值范围是 [-1000000,1000000] 的整数。

示例:

root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8

      10
     /  \
    5   -3
   / \    \
  3   2   11
 / \   \
3  -2   1

返回 3。和等于 8 的路径有:

1.  5 -> 3
2.  5 -> 2 -> 1
3.  -3 -> 11

  1. 双重递归
class Solution {
    public int pathSum(TreeNode root, int sum) {
        if (root == null) {
            return 0;
        }
        return pathSum(root.left, sum) + pathSum(root.right, sum)
            + help(root, sum);
    }

    public int help(TreeNode root, int sum){
        if (root == null) {
            return 0;
        }
        return (sum == root.val ? 1 : 0) + help(root.left, sum - root.val) + help(root.right, sum - root.val);
    }
}
  1. 前缀和
class Solution {
    public int pathSum(TreeNode root, int sum) {
        Map<Integer, Integer> map = new HashMap<>(4);
        map.put(0, 1);
        return helper(root, map, sum, 0);
    }

    public int helper(TreeNode node, Map<Integer, Integer> map, int sum, int pathSum) {
        if (node == null) {
            return 0;
        }
        int curSum = pathSum + node.val;
        int res = map.getOrDefault(curSum - sum, 0);
        map.put(curSum, map.getOrDefault(curSum, 0) + 1);
        res += helper(node.left, map, sum, curSum);
        res += helper(node.right, map, sum, curSum);
        map.put(curSum, map.get(curSum) - 1);
        return res;
    }
}