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;
}