forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution.java
35 lines (33 loc) · 952 Bytes
/
Solution.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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int pathSum(TreeNode root, int sum) {
if (root == null) return 0;
int res = 0;
LinkedList<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
res += solution(node, sum);
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
return res;
}
private int solution(TreeNode root, int sum) {
if (root == null) return 0;
int res = sum == root.val ? 1 :
return solution(root.left, sum - root.val) + solution(root.right, sum - root.val) + res;
}
}