-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweek 3 113. Path Sum II
More file actions
43 lines (37 loc) · 1.06 KB
/
week 3 113. Path Sum II
File metadata and controls
43 lines (37 loc) · 1.06 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
43
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
ArrayList <ArrayList<Integer>> result = new ArrayList <ArrayList<Integer>>();
if(root == null)
return result;
ArrayList<Integer> l = new ArrayList<Integer>();
l.add(root.val);
dfs(root, sum - root.val, result, l);
return result;
}
public void dfs(TreeNode t, int sum, ArrayList<ArrayList<Integer>> result, ArrayList<Integer> l) {
if(t.left==null && t.right==null && sum==0){
ArrayList<Integer> temp = new ArrayList<Integer>();
temp.addAll(l);
result.add(temp);
}
if(t.left != null){
l.add(t.left.val);
dfs(t.left, sum-t.left.val, result, l);
l.remove(l.size()-1);
}
if(t.right!=null){
l.add(t.right.val);
dfs(t.right, sum-t.right.val, result, l);
l.remove(l.size()-1);
}
}
}