-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path437.java
64 lines (56 loc) · 942 Bytes
/
437.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
63
64
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 count;
int target;
public int pathSum(TreeNode root, int targetSum) {
if (root == null) {
return 0;
}
count = 0;
target = targetSum;
path(root);
return count;
}
void path(TreeNode root) {
if (root == null)
return;
take(root, 0);
path(root.left);
path(root.right);
}
void take(TreeNode root, int val) {
if (root == null)
return;
val += root.val;
if (val == target)
count++;
take(root.left, val);
take(root.right, val);
}
}
/*
*
* [5,4,8,11,null,13,4,7,2,null,null,5,1]
* 22
*
* expected 3
*
* [1,null,2,null,3,null,4,null,5]
* 3
*
* expected 2
*/