-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution0437.java
More file actions
42 lines (34 loc) · 878 Bytes
/
Solution0437.java
File metadata and controls
42 lines (34 loc) · 878 Bytes
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
package leetcode;
import ds.tree.TreeNode;
/**
* @author xiangdotzhaoAtwoqutechcommacom
* @date 2019/12/20
*/
public class Solution0437 {
public int pathSum(TreeNode root, int sum) {
if (root == null) {
return 0;
}
return findPath(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum);
}
/**
* 以 root 为根节点的树中找一个 path sums up to sum
*
* @param root root
* @param sum sum
* @return amount
*/
private int findPath(TreeNode root, int sum) {
if (root == null) {
return 0;
}
int res = 0;
if (root.val == sum) {
res += 1;
// cannot return directly
}
res += findPath(root.left, sum - root.val);
res += findPath(root.right, sum - root.val);
return res;
}
}