forked from hongtaocai/code_interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpathsum2.java
More file actions
executable file
·34 lines (30 loc) · 1.03 KB
/
pathsum2.java
File metadata and controls
executable file
·34 lines (30 loc) · 1.03 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) {
// Start typing your Java solution below
// DO NOT write main() function
if(root==null) return new ArrayList<ArrayList<Integer>>();
if(root.left==null && root.right==null && sum == root.val) {
ArrayList<Integer> k = new ArrayList<Integer>();
k.add(root.val);
ArrayList<ArrayList<Integer>> kk = new ArrayList<ArrayList<Integer>>();
kk.add(k);
return kk;
}
ArrayList<ArrayList<Integer>> res1 = pathSum(root.left,sum-root.val);
ArrayList<ArrayList<Integer>> res2 = pathSum(root.right,sum-root.val);
res1.addAll(res2);
for(ArrayList<Integer> e : res1 ){
e.add(0,root.val);
}
return res1;
}
}