-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPath Sum II.java
More file actions
42 lines (40 loc) · 1.14 KB
/
Copy pathPath Sum II.java
File metadata and controls
42 lines (40 loc) · 1.14 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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
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>();
if(root == null)
return result;
helperFunc(root, sum, 0, list, result);
return result;
}
static void helperFunc(TreeNode root, int sum, int pathsum, List<Integer> list, List<List<Integer>> result)
{
if(root == null)
{
return;
}
pathsum += root.val;
list.add(root.val);
if(pathsum == sum && root.left == null && root.right == null)
{
result.add(new ArrayList(list));
list.remove(list.size()-1);
return;
}
else
{
helperFunc(root.left, sum, pathsum, list, result);
helperFunc(root.right, sum, pathsum, list, result);
}
list.remove(list.size()-1);
}
}