forked from JFulgoni/Java-Practice
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPathSum.java
More file actions
74 lines (66 loc) · 1.79 KB
/
Copy pathPathSum.java
File metadata and controls
74 lines (66 loc) · 1.79 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package john_test;
import java.util.ArrayList;
import java.util.List;
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class PathSum{
public static boolean hasPathSum(TreeNode root, int sum){
if(root == null){
return false;
}
if(root.left == null && root.right == null){
return sum == root.val;
}
return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
}
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
List<Integer> path = new ArrayList<Integer>();
findPathSum(root, sum, result, path);
return result;
}
public void findPathSum(TreeNode root, int sum, List<List<Integer>> result, List<Integer> path){
if(root == null){
return;
}
path.add(root.val);
//root.val == sum &&
if(root.left == null && root.right == null){
List<Integer> temp = new ArrayList<Integer>(path);
//temp.add(root.val);
result.add(temp);
}
/*
* this part is similar to the find path function from before
* once we
*/
findPathSum(root.left, sum - root.val, result, path);
findPathSum(root.right, sum - root.val, result, path);
path.remove(path.size() - 1);
}
public static void main(String[] args){
TreeNode root = new TreeNode(10);
root.add(8);
root.add(4);
root.add(9);
root.add(20);
root.add(30);
root.add(11);
System.out.println(root.byLevel());
if(hasPathSum(root, 10)){
System.out.println("Yes");
}
else{
System.out.println("No");
}
PathSum ps = new PathSum();
System.out.println(ps.pathSum(root, 11));
}
}