-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbt-path-sum.java
More file actions
38 lines (38 loc) · 1.35 KB
/
bt-path-sum.java
File metadata and controls
38 lines (38 loc) · 1.35 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
public class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
// Start typing your Java solution below
// DO NOT write main() function
if(root==null) return false;
if(root.left==null&&root.right==null) return sum==root.val;
//if(hasPathSum(root.left,sum-root.val)) return true;
return hasPathSum(root.left,sum-root.val)||hasPathSum(root.right,sum-root.val);
}
}
public class Solution {
ArrayList<ArrayList<Integer>> r;
public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
// Start typing your Java solution below
// DO NOT write main() function
r=new ArrayList<ArrayList<Integer>>();
if(root==null) return r;
path(root,sum,new ArrayList<Integer>());
return r;
}
public void path(TreeNode root,int sum,ArrayList<Integer> sofar) {
if(root==null) return;
//sofar.add(root.val);
if(root.left==null&&root.right==null) {
if(root.val==sum) {
ArrayList<Integer> cp=new ArrayList<Integer>(sofar);
cp.add(root.val);
r.add(cp);
//return;
}
return;
}
sofar.add(root.val);
path(root.left,sum-root.val,sofar);
path(root.right,sum-root.val,sofar);
sofar.remove(sofar.size()-1);
}
}