-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPathSum.java
More file actions
49 lines (43 loc) · 1.25 KB
/
Copy pathPathSum.java
File metadata and controls
49 lines (43 loc) · 1.25 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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null) return false;
int result = 0;
ArrayList<Integer> myList = new ArrayList<Integer>();
helper(root, result, myList);
if(myList.contains(sum)){
return true;
}else {
return false;
}
}
public void helper(TreeNode root, int result, ArrayList<Integer> myList){
if (root == null) {
return;
}else {
result += root.val;
if (root.left != null) helper(root.left, result, myList);
if (root.right != null) helper(root.right, result, myList);
if (root.left == null && root.right == null) myList.add(result);
}
}
}
/**
* Internet method,
*
*public boolean hasPathSum(TreeNode root, int sum) {
if(root == null)
return false;
if(root.left == null && root.right==null && root.val==sum)
return true;
return hasPathSum(root.left, sum-root.val) || hasPathSum(root.right, sum-root.val);
}
*/