Repository navigation
Expand file tree
/
Copy pathproblem437.java
More file actions
84 lines (58 loc) · 2.05 KB
/
Copy pathproblem437.java
File metadata and controls
84 lines (58 loc) · 2.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
//437. Path Sum III
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) { this.val = val; }
}
public class problem437 {
public static int traverse(TreeNode r , int targetSum, HashMap<Long,Integer> hm , long runsum)
{
if(r==null)
return 0;
runsum+=r.val;
int count = hm.getOrDefault(runsum-targetSum, 0);
hm.put(runsum, hm.getOrDefault(runsum, 0)+1);
count+= traverse(r.left, targetSum, hm, runsum)+traverse(r.right, targetSum, hm, runsum);
hm.put(runsum, hm.get(runsum) - 1);
return count ;
}
public static int pathSum(TreeNode root, int targetSum) {
HashMap<Long,Integer> hm = new HashMap<>();
hm.put((long)0, 1);
return traverse(root, targetSum,hm,0);
}
// Function to build a binary tree from an array (Level-Order Representation)
public static TreeNode buildTree(Integer[] arr) {
if (arr.length == 0 || arr[0] == null) return null;
TreeNode root = new TreeNode(arr[0]);
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
int i = 1;
while (!queue.isEmpty() && i < arr.length) {
TreeNode current = queue.poll();
// Left child
if (i < arr.length && arr[i] != null) {
current.left = new TreeNode(arr[i]);
queue.add(current.left);
}
i++;
// Right child
if (i < arr.length && arr[i] != null) {
current.right = new TreeNode(arr[i]);
queue.add(current.right);
}
i++;
}
return root;
}
public static void main(String[] args) {
Integer[] treeArray = {10, 5, -3, 3, 2, null, 11, 3, -2, null, 1};
// Construct the tree
TreeNode root = buildTree(treeArray);
System.out.println(root.val);
System.out.println(pathSum(root, 8));
}
}