forked from forging2012/JavaArithmetic
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode113.java
More file actions
52 lines (37 loc) · 1.31 KB
/
LeetCode113.java
File metadata and controls
52 lines (37 loc) · 1.31 KB
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
46
47
48
49
50
51
52
package LeetCode;
import java.util.LinkedList;
import java.util.List;
public class LeetCode113 {
public class TreeNode {
int val;
LeetCode113.TreeNode left;
LeetCode113.TreeNode right;
TreeNode(int x) {
val = x;
}
}
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> ans = new LinkedList<>();
List<Integer> result = new LinkedList<>();
path(root, sum, ans, result);
return ans;
}
public void path(TreeNode root, int sum, List<List<Integer>> ans, List<Integer> result) {
if (root == null) return;
// 先放入temp中
result.add(new Integer(root.val));
if (root.left == null && root.right == null && sum == root.val) {
// 如果是叶子节点,条件也符合,放入结果中
ans.add(new LinkedList(result));
/* result.remove(result.size() - 1);
return;*/
} else {
path(root.left, sum - root.val, ans, result);
path(root.right, sum - root.val, ans, result);
//如果不符合,则去除
result.remove(result.size() - 1);
}
}
}
}