-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathSolution437.java
45 lines (34 loc) · 875 Bytes
/
Solution437.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
package leetcode.tree.dfs;
import leetcode.TreeNode;
public class Solution437 {
int res;
int targetSum;
public int pathSum(TreeNode root, int targetSum) {
this.res = 0;
this.targetSum = targetSum;
doPathSum(root);
return res;
}
private void doPathSum(TreeNode root) {
if (root == null) {
return;
}
doPathSum2(root, root.val);
doPathSum(root.left);
doPathSum(root.right);
}
private void doPathSum2(TreeNode root, long val) {
if (root == null) {
return;
}
if (val == targetSum) {
res++;
}
if (root.left != null) {
doPathSum2(root.left, val + root.left.val);
}
if (root.right != null) {
doPathSum2(root.right, val + root.right.val);
}
}
}