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. CF 335B. Palindrome(DP)

    题目链接 挺好玩的一个题,1Y... #include <cstdio> #include <cstring> #include <iostream> using ...

  2. Android -- ImageSwitch和Gallery 混合使用

    1. 实现效果

  3. Java中UIManager的几种外观的详细讲解

    Java'中的几种Look and Feel 1.Metal风格 (默认) String lookAndFeel = "javax.swing.plaf.metal.MetalLookAnd ...

  4. Spring MVC和Struts2的比较(二)

    1.Spring MVC的controller+command object模式比Struts2的Action模式更安全一些.而在Struts2中,自动数据绑定发生在Action对象上.这样,在Act ...

  5. JSch - Java实现的SFTP(文件下载详解篇)

    上一篇讲述了使用JSch实现文件上传的功能,这一篇主要讲述一下JSch实现文件下载的功能.并介绍一些SFTP的辅助方法,如cd,ls等. 同样,JSch的文件下载也支持三种传输模式:OVERWRITE ...

  6. JS开发HTML5游戏《神奇的六边形》(二)

    近期出现一款魔性的消除类HTML5游戏<神奇的六边形>,今天我们一起来看看如何通过开源免费的青瓷引擎(www.zuoyouxi.com)来实现这款游戏. (点击图片可进入游戏体验) 因内容 ...

  7. android基础知识之一

    1:Android系统架构(重点) 分层的架构 JNI java native interface 1.application :应用层 : java 2.application framework ...

  8. javascript 百度地图

    官方地址 http://lbsyun.baidu.com/index.php?title=jspopular 示例地址 http://developer.baidu.com/map/jsdemo.ht ...

  9. C# 常用类

    一.Convert 主要用于数据类型的转换,常用的静态方法有: Convert.ToSingle():把数据转换为单精度浮点数,参数常为字符串 Convert.ToDouble():转为双精度浮点数 ...

  10. 【7集iCore3基础视频】7-2 iCore3原理图介绍

    iCore3原理图介绍: 高清源视频:http://pan.baidu.com/s/1hsPkifM 密码:ei8ciCore3 购买链接:https://item.taobao.com/item.h ...