Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java return statement strange behaviour

Tags:

java

I am solving the Path Sum problem from leetcode and I don't understand the behavior of the return statement. I have a tree with 2 nodes. The root node has value 1, and its left child has value 2.

I have to return true if the sum of the 2 nodes is 3, which obviously it is, but somehow the program continues to run even after it reaches return true.

public class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if (root != null) return hasPathSumRec(root, 0, sum);
        else return false;
    }

    public boolean hasPathSumRec(TreeNode node, int currentSum, int sum) {
        if (isLeaf(node) && sum == currentSum + node.val) {
            return true;
        } else {
            if (node.left != null) {
                hasPathSumRec(node.left, currentSum + node.val, sum);
            }
            if (node.right != null) {
                hasPathSumRec(node.right, currentSum + node.val, sum);
            }
        }
        return false;
    }

    public boolean isLeaf(TreeNode node) {
        return node.left == null && node.right == null;

    ....
}

My question is - how does the program reach return false even though it goes into return true?

like image 594
gabyk00 Avatar asked Sep 12 '26 13:09

gabyk00


2 Answers

You should use the values returned by the recursive calls :

public boolean hasPathSumRec(TreeNode node, int currentSum, int sum) {
    if (isLeaf(node) && sum == currentSum + node.val) {
        return true;
    } else {
        boolean result = false;
        if (node.left != null) {
            result = result || hasPathSumRec(node.left, currentSum + node.val, sum);
        }
        if (node.right != null) {
            result = result || hasPathSumRec(node.right, currentSum + node.val, sum);
        }
        return result;
    }
    return false;
}

When you ignore them, you reach the return false; statement.

like image 111
Eran Avatar answered Sep 14 '26 03:09

Eran


You appears to have missed two return statements. I think you wanted something like

if (node.left != null) {
  if (hasPathSumRec(node.left, currentSum + node.val, sum)) return true;
}
if (node.right != null) {
  if (hasPathSumRec(node.right, currentSum + node.val, sum)) return true;
}
like image 43
Elliott Frisch Avatar answered Sep 14 '26 03:09

Elliott Frisch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!