forked from tanglu/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpathSumII.java
41 lines (35 loc) · 1.1 KB
/
pathSumII.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
39
40
41
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
void dfs(TreeNode root,int sum, ArrayList<Integer> path, ArrayList<ArrayList<Integer>> result) {
if(root==null)
return ;
path.add(root.val);
if(root.left==null&&root.right==null){
if(root.val==sum) {
ArrayList<Integer> tmp = new ArrayList<Integer>(path);
result.add(tmp);
}
}
if(root.left!=null) {
dfs(root.left,sum - root.val,path,result) ;
}
if(root.right!=null) {
dfs(root.right,sum - root.val, path,result);
}
path.remove(path.size() - 1);
}
public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> path = new ArrayList<Integer>();
dfs(root,sum,path,result);
return result;
}
}