Skip to content

Commit 64a9ece

Browse files
authored
Update and rename Easy/Path Sum III.java to Medium/Path Sum III.java
1 parent 9c98ee4 commit 64a9ece

File tree

2 files changed

+36
-24
lines changed

2 files changed

+36
-24
lines changed

Easy/Path Sum III.java

Lines changed: 0 additions & 24 deletions
This file was deleted.

Medium/Path Sum III.java

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode() {}
8+
* TreeNode(int val) { this.val = val; }
9+
* TreeNode(int val, TreeNode left, TreeNode right) {
10+
* this.val = val;
11+
* this.left = left;
12+
* this.right = right;
13+
* }
14+
* }
15+
*/
16+
class Solution {
17+
public int pathSum(TreeNode root, int targetSum) {
18+
Map<Long, Integer> map = new HashMap<>();
19+
map.put(0L, 1);
20+
int[] count = {0};
21+
preorder(root, 0L, map, count, targetSum);
22+
return count[0];
23+
}
24+
25+
private void preorder(TreeNode root, long currSum, Map<Long, Integer> map, int[] count, int targetSum) {
26+
if (root == null) {
27+
return;
28+
}
29+
currSum += root.val;
30+
count[0] += map.getOrDefault(currSum - targetSum, 0);
31+
map.put(currSum, map.getOrDefault(currSum, 0) + 1);
32+
preorder(root.left, currSum, map, count, targetSum);
33+
preorder(root.right, currSum, map, count, targetSum);
34+
map.put(currSum, map.get(currSum) - 1);
35+
}
36+
}

0 commit comments

Comments
 (0)