forked from chuyi2007/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPathSumII.java
More file actions
39 lines (38 loc) · 1.3 KB
/
PathSumII.java
File metadata and controls
39 lines (38 loc) · 1.3 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
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<ArrayList<Integer>> results
= new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> result = new ArrayList<Integer>();
pathSum(results, result, root, sum);
return results;
}
public void pathSum(ArrayList<ArrayList<Integer>> results, ArrayList<Integer> result,
TreeNode root, int sum){
if(root != null){
if(root.left == null && root.right == null){
if(sum == root.val){
ArrayList<Integer> tmp = new ArrayList<Integer>(result);
tmp.add(root.val);
results.add(tmp);
}
}
else{
result.add(root.val);
pathSum(results, result, root.left, sum - root.val);
pathSum(results, result, root.right, sum - root.val);
result.remove(result.size() - 1);
}
}
}
}