Runtime: 2 ms, faster than 100.00% of Java online submissions for Path Sum III.
In this TC is O(n) ,because we are using HashMap.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int total = 0 ;
public int pathSum(TreeNode root, int target) {
if(root == null){
return 0;
}
HashMap<Integer , Integer> preSum = new HashMap<>();
preSum.put(0,1);
findPathSum(root , 0 , target , preSum);
return total;
}
public void findPathSum(TreeNode node ,int sum,int target,HashMap<Integer , Integer> preSum){
if(node == null){
return ;
}
sum += node.val;
if(preSum.containsKey(sum - target)){
total += preSum.get(sum-target);
}
preSum.put(sum , preSum.getOrDefault(sum,0) + 1);
findPathSum(node.left , sum , target , preSum);
findPathSum(node.right , sum , target , preSum);
preSum.put(sum , preSum.get(sum) - 1);
return;
}
}