-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patha_437.java
More file actions
25 lines (24 loc) · 745 Bytes
/
a_437.java
File metadata and controls
25 lines (24 loc) · 745 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
package datastructure.tree;
/**
* 统计路径和等于一个数的路径数量
*/
public class a_437 {
public int pathSum(TreeNode root, int sum) {
if (root == null) return 0;
int ret = pathSumStartWithRoot(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum);
return ret;
}
private int pathSumStartWithRoot(TreeNode root, int sum) {
if (root == null) return 0;
int ret = 0;
if (root.val == sum) ret++;
ret += pathSumStartWithRoot(root.left, sum-root.val) + pathSumStartWithRoot(root.right, sum-root.val);
return ret;
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
}