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. Android -- 加载布局

    如果在Activity中用到了别的Layout ,比如对话框等,你还要使用对话框中的组件,如TextView等,必须要先加载布局,然后才能使用里面的控件, 如 : View view = View.i ...

  2. 【bzoj1455】罗马游戏 可并堆

    2016-05-31  10:04:41 可并堆的裸题. 左偏树(小根堆为例 性质 1.满足堆的性质,每个节点权值小于左右儿子权值 2.每个节点有dis值,表示子树最浅的叶子深度加1 3.左子树dis ...

  3. Windows Maven package时报错问题的解决

    google了一把,看到别人的说法是Stack size 不够大. Stack Space用来做方法的递归调用时压入Stack Frame.所以当递归调用太深的时候,就有可能耗尽Stack Space ...

  4. 地理数据库的类型geodatabase类型

    地理数据库的类型geodatabase类型 地理数据库是用于保存数据集集合的“容器”.有以下三种类型: 文件地理数据库 - 在文件系统中以文件夹形式存储.每个数据集都以文件形式保存,该文件大小最多可扩 ...

  5. MongoDB的数据库基本操作(一)

    查看当前数据库 MongoDB shell version:1.8.1connecting to:test> dbtest 查看全部数据库列表 >show dbsChatRoom    0 ...

  6. DropDownList 控件不能触发SelectedIndexChanged 事件

    相信DropDownList 控件不能触发SelectedIndexChanged 事件已经不是什么新鲜事情了,原因也无外乎以下几种: 1.DropDownList 控件的属性 AutoPostBac ...

  7. jquery过滤器之:contains()、.filter()

    :contains 选择器选取包含指定字符串的元素. 该字符串可以是直接包含在元素中的文本,或者被包含于子元素中. 经常与其他元素/选择器一起使用,来选择指定的组中包含指定文本的元素,如: $(&qu ...

  8. 常用JQ特效代码

    /** * hhBase 平台js * User: huanhuan * QQ: 651471385 * Email: th.wanghuan@gmail.com * 微博: huanhuan的天使 ...

  9. mysql配置之skip-external-locking

    转载:http://www.kuqin.com/database/20120815/328905.html MySQL的配置文件my.cnf中默认存在一行skip-external-locking的参 ...

  10. 已知树的前序、中序,求后序的c++实现&已知树的后序、中序,求前序的c++实现

    #include"iostream" using namespace std; int pre[30]; int in[30]; int post[30]; int indexOf ...