-
Notifications
You must be signed in to change notification settings - Fork 277
/
PathSumIII.java
62 lines (49 loc) · 1.45 KB
/
PathSumIII.java
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
/**
* 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 PathSumIII {
private int count = 0;
public int pathSum(TreeNode root, int sum) {
if(root==null){
return count;
}
postOrderTraversal(root, sum);
return count;
}
private List<Integer> postOrderTraversal(TreeNode root, int sum) {
if(root==null){
return new ArrayList<>();
}
List<Integer> leftList = postOrderTraversal(root.left, sum);
List<Integer> rightList = postOrderTraversal(root.right, sum);
List<Integer> currList = new ArrayList<>();
// Iterate through the leftList and add root.val to each el
for(Integer leftChild : leftList){
currList.add(leftChild + root.val);
}
// Iterate through the leftList and add root.val to each el
for(Integer rightChild : rightList){
currList.add(rightChild + root.val);
}
// adding root.val in currList
currList.add(root.val);
for(Integer el: currList){
if(el == sum){
count++;
}
}
return currList;
}
}