-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPathSum.java
More file actions
44 lines (40 loc) · 956 Bytes
/
PathSum.java
File metadata and controls
44 lines (40 loc) · 956 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
33
34
35
36
37
38
39
40
41
42
43
44
import java.util.ArrayList;
public class PathSum {
ArrayList<Integer> sums = new ArrayList<Integer>();
public boolean hasPathSum(TreeNode root, int sum) {
int s = 0;
if (root == null) {
if (sum == 0) {
return true;
}
else {
return false;
}
}
preorder(root, 0);
for (Integer x: sums) {
if (x == sum) {
return true;
}
}
return false;
}
public void preorder(TreeNode root, int prev) {
if (root.left == null && root.right == null) {
sums.add(prev + root.val);
return;
}
if (root.left != null) {
preorder(root.left, prev + root.val);
}
if (root.right != null) {
preorder(root.right, prev + root.val);
}
}
public void testSum() {
TreeNode root = new TreeNode(5);
root.left = new TreeNode(3);
root.right = new TreeNode(2);
System.out.println(hasPathSum(root, 6));
}
}