Question -> Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
My Solution ->
public class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if (root == null || sum == 0){
return false;
}
List<Integer> resultSet = new ArrayList<Integer>();
Integer result = root.val;
inorder(root, result, resultSet);
return resultSet.contains(sum);
}
public void inorder(TreeNode root, Integer result, List<Integer> resultSet){
if (root.left == null && root.right == null){
resultSet.add(result);
}
if (root.left != null) {
result += Integer.valueOf(root.left.val);
inorder(root.left, result, resultSet);
}
if (root.right != null) {
result += Integer.valueOf(root.right.val);
inorder(root.right, result, resultSet);
}
}
}
Output ->
Input: [1,-2,-3,1,3,-2,null,-1] 3 Output: true Expected: false
I am really not sure where I am going wrong with this. I tried playing with the int and Integer type options for result , but it didn't work. Please help.