I am working on Leet Code problem 112. Path Sum:
Given the
root
of a binary tree and an integertargetSum
, returntrue
if the tree has a root-to-leaf path such that adding up all the values along the path equalstargetSum
.A leaf is a node with no children.
I the code below trying to solve it, but apparently it isn't correct as I keep running into failed test cases.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if(root.left==null&&root.right==null&&targetSum-root.val ==0)
return true;
else{
if(root.right!= null){
hasPathSum(root.right, targetSum-root.val);
}
if(root.left!=null) {
hasPathSum(root.left, targetSum-root.val);
}
} return false;
}
}
What is wrong with this code?