-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPath Sum II
More file actions
34 lines (34 loc) · 1.22 KB
/
Path Sum II
File metadata and controls
34 lines (34 loc) · 1.22 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
/**
* 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) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if(root == null) return result;
helpler(result, new ArrayList<Integer>(), root, sum);
return result;
}
private void helpler(ArrayList<ArrayList<Integer>> result, ArrayList<Integer> paths, TreeNode root, int sum)
{
if(root == null) return;
paths.add(root.val);
if(root.left == null && root.right == null && root.val == sum)
{
ArrayList<Integer> temp = new ArrayList<Integer>(paths); //has to copy, or will cause the Output Limit Exceeded error
result.add(temp);
}
else{
helpler(result, paths, root.left, sum-root.val);
helpler(result, paths, root.right, sum-root.val);
}
paths.remove(paths.size()-1);
}
}