Java return 语句奇怪的行为

标签 java

我正在解决 leetcode 中的路径总和问题,但我不明白 return 语句的行为。我有一棵有 2 个节点的树。根节点的值为 1,其左子节点的值为 2。

如果 2 个节点的总和为 3,我必须返回 true,显然确实如此,但不知何故,即使在达到 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;

    ....
}

我的问题是 - 即使程序进入了return true,但它如何达到return false

最佳答案

您应该使用递归调用返回的值:

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;
}

当您忽略它们时,就会到达 return false; 语句。

关于Java return 语句奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26595455/

相关文章:

java - 对 Java EE Web 应用程序的外部访问

java - 如何在 jOOQ 查询中使用 Postgres 的 to_char?

java - Netbeans 无法识别 import java.awt.event.ActionEvent 和 import java.awt.event.ActionListener

java - Java中根据出现次数分割字符串

java - 在 Restful-WebService 响应中包含所有 @OneToMany 实体?

java - RedisTokenstore : Cannot cast . ..用户到...用户

java - JTable 行总计颜色编码标签

java - 正则表达式仅允许两种模式中的一种

java - 接收消息调用存储过程时找不到对应参数

java - JMS 应用程序给出错误