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?
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With