Leetcode: Path Sum III
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的更多相关文章
- [LeetCode] Path Sum III 二叉树的路径和之三
You are given a binary tree in which each node contains an integer value. Find the number of paths t ...
- Python3解leetcode Path Sum III
问题描述: You are given a binary tree in which each node contains an integer value. Find the number of p ...
- 第34-3题:LeetCode437. Path Sum III
题目 二叉树不超过1000个节点,且节点数值范围是 [-1000000,1000000] 的整数. 示例: root = [10,5,-3,3,2,null,11,3,-2,null,1], sum ...
- 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 ...
- 【leetcode】437. Path Sum III
problem 437. Path Sum III 参考 1. Leetcode_437. Path Sum III; 完
- 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 ...
- [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 ...
- [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 ...
- [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 ...
随机推荐
- 初识GO语言——安装Go语言
本文包括:1)安装Go语言.2)运行第一个Go语言.3)增加vim中对Go语言的高亮支持. 1.安装Go语言 本文采用源码安装Go语言,Go语言的源代码在百度网盘 http://pan.baidu.c ...
- 已知树的前序、中序,求后序的java实现&已知树的后序、中序,求前序的java实现
public class Order { int findPosInInOrder(String str,String in,int position){ char c = str.charAt(po ...
- [CareerCup] 17.1 Swap Number In Place 互换位置
17.1 Write a function to swap a number in place (that is, without temporary variables). 这道题让我们交换两个数, ...
- WinForm timer控件
timer 控件:按用户定义的时间间隔引发的事件 属性: Enabled 是否启用: Interval 事件发生的事件间隔,单位是毫秒 事件只有一个:Tick 事件经过指定的时间间隔 ...
- MRP运算生成采购单时间的逻辑
由MRP运算产生的采购单日期,由生产单指定的安排计划日期.公司设置里的采购提前期和隐藏的供应商供货提前期三个字段共同决定. 可以很容易的在系统中找到,供应商供货提前期,需要在产品视图中将字段selle ...
- Struts的文件下载功能实现代码
Action: package com.tengfeiyang.action; import java.io.File; import java.io.FileInputStream; import ...
- E: dpkg 被中断,您必须手工运行 sudo dpkg --configure -a 解决此问题。
学习 : http://blog.csdn.net/darennet/article/details/9009361 http://www.uedsc.com/dpkg-sudo-dpkg-confi ...
- php继承后构造函数的特性
在5.x版本的php中: 如果父类有构造函数,它的子类也有构造函数,那么在运行子类时就“不会执行父类的构造函数”. 要想执行父类的构造函数,需要在子类的构造函数中加上: parent::__const ...
- html5的本地存储
转载1:http://www.cnblogs.com/fly_dragon/p/3946012.html 转载2:http://www.cnblogs.com/xiaowei0705/archive/ ...
- thinkphp 的save()不能更新数据解决办法
用save()方法始终更新不了数据,又不显示明确的错误信息,找了好久才在手册里看到一句至关重要的话: 为了保证数据库的安全,避免出错更新整个数据表,如果没有任何更新条件,数据对象本身也不包含主键字段的 ...