You are given a binary tree in which each node contains an integer value.

Find the number of paths that sum to a given value.

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

The tree has no more than , nodes and the values are in the range -,, to ,,.

Example:

root = [,,-,,,null,,,-,null,], sum = 

     /  \
-
/ \ \ / \ \
- Return . The paths that sum to are: . ->
. -> ->
. - ->

Add the prefix sum to the hashMap, and check along path if hashMap.contains(pathSum+cur.val-target);

My Solution

 /**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int pathSum(TreeNode root, int sum) {
if (root == null) return 0;
ArrayList<Integer> res = new ArrayList<Integer>();
res.add(0);
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(0, 1);
helper(root, sum, 0, res, map);
return res.get(0);
} public void helper(TreeNode cur, int target, int pathSum, ArrayList<Integer> res, HashMap<Integer, Integer> map) {
if (map.containsKey(pathSum+cur.val-target)) {
res.set(0, res.get(0) + map.get(pathSum+cur.val-target));
}
if (!map.containsKey(pathSum+cur.val)) {
map.put(pathSum+cur.val, 1);
}
else map.put(pathSum+cur.val, map.get(pathSum+cur.val)+1);
if (cur.left != null) helper(cur.left, target, pathSum+cur.val, res, map);
if (cur.right != null) helper(cur.right, target, pathSum+cur.val, res, map);
map.put(pathSum+cur.val, map.get(pathSum+cur.val)-1);
}
}

一个更简洁的solution: using HashMap to store ( key : the prefix sum, value : how many ways get to this prefix sum) , and whenever reach a node, we check if prefix sum - target exists in hashmap or not, if it does, we added up the ways of prefix sum - target into res.

     public int pathSum(TreeNode root, int sum) {
Map<Integer, Integer> map = new HashMap<>();
map.put(0, 1); //Default sum = 0 has one count
return backtrack(root, 0, sum, map);
}
//BackTrack one pass
public int backtrack(TreeNode root, int sum, int target, Map<Integer, Integer> map){
if(root == null)
return 0;
sum += root.val;
int res = map.getOrDefault(sum - target, 0); //See if there is a subarray sum equals to target
map.put(sum, map.getOrDefault(sum, 0)+1);
//Extend to left and right child
res += backtrack(root.left, sum, target, map) + backtrack(root.right, sum, target, map);
map.put(sum, map.get(sum)-1); //Remove the current node so it wont affect other path
return res;
}

Leetcode: Path Sum III的更多相关文章

  1. [LeetCode] Path Sum III 二叉树的路径和之三

    You are given a binary tree in which each node contains an integer value. Find the number of paths t ...

  2. Python3解leetcode Path Sum III

    问题描述: You are given a binary tree in which each node contains an integer value. Find the number of p ...

  3. 第34-3题:LeetCode437. Path Sum III

    题目 二叉树不超过1000个节点,且节点数值范围是 [-1000000,1000000] 的整数. 示例: root = [10,5,-3,3,2,null,11,3,-2,null,1], sum ...

  4. 47. leetcode 437. Path Sum III

    437. Path Sum III You are given a binary tree in which each node contains an integer value. Find the ...

  5. 【leetcode】437. Path Sum III

    problem 437. Path Sum III 参考 1. Leetcode_437. Path Sum III; 完

  6. leetcode 112. Path Sum 、 113. Path Sum II 、437. Path Sum III

    112. Path Sum 自己的一个错误写法: class Solution { public: bool hasPathSum(TreeNode* root, int sum) { if(root ...

  7. [LeetCode] Path Sum II 二叉树路径之和之二

    Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given su ...

  8. [LeetCode] Path Sum 二叉树的路径和

    Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all ...

  9. [LeetCode] Path Sum IV 二叉树的路径和之四

    If the depth of a tree is smaller than 5, then this tree can be represented by a list of three-digit ...

随机推荐

  1. 【异常】java.lang.NoClassDefFoundError: com/lowagie/text/pdf/PdfContentByte

    异常信息:   java.lang.NoClassDefFoundError: com/lowagie/text/pdf/PdfContentByte  at com.star.sms.busines ...

  2. Oracle 新手问答

    存储过程中,return后,如果没有写明提交(commit)或回滚(rollback),会默认提交吗?答:不会.如果修改了数据,又没有写明,则会将数据锁定在那里! 存储过程中,调用子存储过程异常时,在 ...

  3. 创建和使用动态链接库 (C++)

    创建和使用动态链接库 (C++) 转载:http://msdn.microsoft.com/zh-cn/library/ms235636.aspx 此分步演练演示如何创建用于 C++ 应用的动态链接库 ...

  4. MAT(Memory Analyzer Tool)工具入门介绍

    1.MAT是什么? MAT(Memory Analyzer Tool),一个基于Eclipse的内存分析工具,是一个快速.功能丰富的JAVA heap分析工具,它可以帮助我们查找内存泄漏和减少内存消耗 ...

  5. linux修改时区为中国时区(北京)

    cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime

  6. Java.lang.NoSuchFieldError: INSTANCE异常

    解决方案: java.lang.NoSuchFieldError: INSTANCE异常. 1.jar包重复了. 2.版本还不相同,如果包的版本不同也会报相应的错,不过一般情况自己导入的jar包主要看 ...

  7. 【android tools】内存、网络、界面性能响应优化的工具

    一.性能优化工具 性能分析,我理解有内存性能,IO性能, 界面性能,耗电等. 内存性能,用debuggable的app结合mat等专业工具可以分析.另外最近的Leakcanary很好用,但是要手动加入 ...

  8. [CareerCup] 17.12 Sum to Specific Value 和为特定数

    17.12 Design an algorithm to find all pairs of integers within an array which sum to a specified val ...

  9. sbt commands

    速查手册 常用命令 actions – 显示对当前工程可用的命令 update – 下载依赖 compile – 编译代码 test – 运行测试代码 package – 创建一个可发布的jar包 p ...

  10. Linux下安装PHP

    从php官网下载好需要php的压缩包,我下的是5.5.37版, 解压:# tar -xvf php-5.5.37.tar.gz 移至解压出的文件夹:# cd php-5.5.37 检查安装环境:# . ...