Java recursive


  • 0
    R

    public class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
    if(root == null && sum==0)
    return true;

    if(root == null && sum !=0 )
    return false;

    return (hasPathSum(root.left,sum-root.val) || hasPathSum(root.right,sum-root.val));

    }
    

    }


  • 1
    R

    this doesnt work for base condition when root==null and sum==0
    expected output=false;
    your code returns true;

    make modification

    if(root==null)
    return false;

    if(root.val==sum && root.right==null && root.left==null)
    return true;
    return (hasPathSum(root.left,sum-root.val) || hasPathSum(root.right,sum-root.val));


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.