[LeetCode] 437. Path Sum III

Given the root of a binary tree and an integer targetSum, return the number of paths where the sum of the values along the path equals targetSum.

The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).

Example 1:

Input: root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8
Output: 3
Explanation: The paths that sum to 8 are shown.

Example 2:

Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
Output: 3

Constraints:

  • The number of nodes in the tree is in the range [0, 1000].
  • -109 <= Node.val <= 109
  • -1000 <= targetSum <= 1000

路径总和 III。

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

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

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

题意和前两个版本类似,但是这个题找的路径和,起点可以不是根节点,问满足路径和为 sum 的路径有多少。

思路是前缀和。利用前缀和的思路,递归统计你遍历到的子树上的前缀和 presum 是多少,并将这个前缀和存入 hashmap。其他的部分就是很常规的前序遍历。注意最后一个 case 会导致 Integer 越界,需要用 long 型。

时间O(n) - 树有 n 个节点

空间O(n) - hashmap

Java实现

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode() {}
 8  *     TreeNode(int val) { this.val = val; }
 9  *     TreeNode(int val, TreeNode left, TreeNode right) {
10  *         this.val = val;
11  *         this.left = left;
12  *         this.right = right;
13  *     }
14  * }
15  */
16 class Solution {
17     int count = 0;
18     
19     public int pathSum(TreeNode root, int targetSum) {
20         HashMap<Long, Integer> map = new HashMap<>();
21         map.put(0L, 1);
22         helper(root, 0L, targetSum, map);
23         return count;
24     }
25     
26     private void helper(TreeNode root, long curSum, int targetSum, HashMap<Long, Integer> map) {
27         if (root == null) {
28             return;
29         }
30         curSum += root.val;
31         if (map.containsKey(curSum - targetSum)) {
32             count += map.get(curSum - targetSum);
33         }
34         map.put(curSum, map.getOrDefault(curSum, 0) + 1);
35         helper(root.left, curSum, targetSum, map);
36         helper(root.right, curSum, targetSum, map);
37         map.put(curSum, map.get(curSum) - 1);
38     }
39 }

 

前缀和prefix sum题目总结

LeetCode 题目总结

posted @ 2020-07-30 07:11  CNoodle  阅读(185)  评论(0编辑  收藏  举报