我正在解决来自leetcode的Path Sum问题,我不明白return语句的行为。我有一棵有2个节点的树。根节点的值为1,其左侧的子节点的值为2.Java返回语句奇怪的行为
如果2个节点的总和为3,这显然是它,但是不知何故程序在达到它之后仍会继续运行返回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;
....
}
我的问题是 - 如何计划达到return false
即使它进入return true
?