Boolean value problem with Path Sum


  • 0
    L
        if (root == null) {
            return false;
        }
        
        int subSum = sum - root.val;
        if (subSum == 0 && root.left == null && root.right == null) {
            return true;
        }
        
        boolean subResult = false;
        if (root.left != null) {
            subResult = subResult || hasPathSum(root.left, subSum);
            // it won't work if I can to 
            subResult = false || hasPathSum(root.left, subSum);
        }
        
        if (root.right != null) {
            subResult = subResult || hasPathSum(root.right, subSum);
            // it won't work if I can to 
            subResult = false || hasPathSum(root.left, subSum);
        }
        
        return subResult;
    

    From the comments above, I am so curious why it's not working for changing to use false inside the || statement. Any ideas?

    Here is the error:

    [1,-2,3], -1

  • 1
    C

    The value of subResult has been changed after executing following statement:

    if (root.left != null) {
            subResult = subResult || hasPathSum(root.left, subSum);
            // it won't work if I can to 
            subResult = false || hasPathSum(root.left, subSum);
        }
    

    Hence in second statement:

    if (root.right != null) {
            subResult = subResult || hasPathSum(root.right, subSum);
            // it won't work if I can to 
            subResult = false || hasPathSum(root.left, subSum);
        }
    

    You cannot use false to replace subResult anymore. Otherwise, why don't you just use subResult = hasPathSum(root.left, subSum) ? Since false || sth is always equivalent to sth.

    Hope this is helpful.


Log in to reply
 

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