-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpath-sum.java
More file actions
31 lines (28 loc) · 850 Bytes
/
path-sum.java
File metadata and controls
31 lines (28 loc) · 850 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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
List<Integer> result = new ArrayList<Integer>();
int pathsum = 0;
result = pathSum(root,pathsum,result);
for(int n : result){
if(sum == n) return true;
}
return false;
}
public List<Integer> pathSum(TreeNode root,int pathsum,List<Integer> result){
if(root==null) return result;
pathsum = pathsum + root.val;
if(root.left == null && root.right == null) result.add(pathsum);
pathSum(root.left,pathsum,result);
pathSum(root.right,pathsum,result);
return result;
}
}