原题
给定一个二叉树的根节点 root ,和一个整数 targetSum ,求该二叉树里节点值之和等于 targetSum 的 路径 的数目。
路径 不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点)。
输入: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
root =
[1000000000,1000000000,null,294967296,null,1000000000,null,1000000000,null,1000000000]
targetSum =0
输出 0
代码思路:
由于整数溢出问题,这些大数相加会溢出:
-
1000000000 + 1000000000 = 2000000000 (正常)
-
2000000000 + 294967296 = 2294967296 > 2^31-1 = 2147483647
-
发生整数溢出,后续计算都不准确
/**
* 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 {
public int pathSum(TreeNode root, int targetSum) {
if(root==null){
return 0;
}
Map<Long,Integer> map = new HashMap<>();
map.put(0L,1);
Long sum =0L;
return deepSum(root,targetSum,sum,map);
}
public static int deepSum(TreeNode root, int targetSum, Long sum ,Map<Long,Integer> map){
if(root!=null){
sum+=root.val;
}
int count = 0;
if(map.containsKey(sum-targetSum)){
count+=map.get(sum-targetSum);
}
map.put(sum,map.getOrDefault(sum,0)+1);
Map<Long,Integer> map1 = new HashMap<>();
for(Long x:map.keySet()){
map1.put(x,map.get(x));
}
if(root.left!=null){
count+=deepSum(root.left,targetSum,sum,map1);
}
if(root.right!=(null)){
count+=deepSum(root.right,targetSum,sum,map);
}
return count;
}
}

优化更新:
/**
* 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 {
public int pathSum(TreeNode root, int targetSum) {
if(root==null){
return 0;
}
Map<Long,Integer> map = new HashMap<>();
map.put(0L,1);
Long sum =0L;
return deepSum(root,targetSum,sum,map);
}
public static int deepSum(TreeNode root, int targetSum, Long sum ,Map<Long,Integer> map){
if(root!=null){
sum+=root.val;
}
int count = 0;
if(map.containsKey(sum-targetSum)){
count+=map.get(sum-targetSum);
}
map.put(sum,map.getOrDefault(sum,0)+1);
if(root.left!=null){
count+=deepSum(root.left,targetSum,sum,map);
}
if(root.right!=(null)){
count+=deepSum(root.right,targetSum,sum,map);
}
//退出当前节点时
map.put(sum,map.getOrDefault(sum,0)-1);
return count;
}
}


1037

被折叠的 条评论
为什么被折叠?



