-
Notifications
You must be signed in to change notification settings - Fork 4
/
113_pathSum2.java
38 lines (35 loc) · 1.11 KB
/
113_pathSum2.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
36
37
38
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
List<Integer> list = new ArrayList<Integer>();
dfs(root,sum,0,list,result);
return result;
}
public void dfs(TreeNode root, int sum, int current, List<Integer> list, List<List<Integer>> result){
if(root == null) return;
current += root.val;
list.add(root.val);
if(root.left == null && root.right == null && sum == current){
List<Integer> copy = new ArrayList<Integer>(list);
result.add(copy);
return;
}
if(root.left!=null){
dfs(root.left,sum,current,list,result);
list.remove(list.size()-1);
}
if(root.right!=null){
dfs(root.right,sum,current,list,result);
list.remove(list.size()-1);
}
}
}