-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPathSumInBT2.java
More file actions
32 lines (30 loc) · 989 Bytes
/
PathSumInBT2.java
File metadata and controls
32 lines (30 loc) · 989 Bytes
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
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class PathSumInBT2 {
public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>();
solve(root, sum, ans, new ArrayList<Integer>());
return ans;
}
void solve(TreeNode root, int sum, ArrayList<ArrayList<Integer>> ans, ArrayList<Integer> tmp){
if(root == null) return;
tmp.add(root.val);
if(root.left == null && root.right == null){
if(sum == root.val){
ArrayList<Integer> list = new ArrayList<Integer>(tmp);
ans.add(list);
}
}else{
solve(root.left, sum - root.val, ans, tmp);
solve(root.right, sum - root.val, ans, tmp);
}
tmp.remove(tmp.size() -1);
}
}