Skip to content

Commit 04e0a40

Browse files
committed
add 113
1 parent 4e59fe5 commit 04e0a40

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

easy/113-path-sum-2.java

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode() {}
8+
* TreeNode(int val) { this.val = val; }
9+
* TreeNode(int val, TreeNode left, TreeNode right) {
10+
* this.val = val;
11+
* this.left = left;
12+
* this.right = right;
13+
* }
14+
* }
15+
*/
16+
class Solution {
17+
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
18+
List<List<Integer>> answer = new ArrayList<>();
19+
20+
solve(root, targetSum, new ArrayList<Integer>(), answer);
21+
22+
return answer;
23+
}
24+
25+
void solve(TreeNode root, int sum, List<Integer> cur, List<List<Integer>> answer) {
26+
if (root == null) {
27+
return;
28+
}
29+
30+
cur.add(root.val);
31+
if (root.val == sum && root.left == null && root.right == null) {
32+
answer.add(new ArrayList<>(cur));
33+
} else {
34+
solve(root.left, sum - root.val, cur, answer);
35+
solve(root.right, sum - root.val, cur, answer);
36+
}
37+
38+
cur.remove(cur.size() - 1);
39+
}
40+
}

0 commit comments

Comments
 (0)