为什么这个二进制搜索成功中间的返回值被忽略?

bee*_*tty 1 java return-value

我仍然对二叉树最大路径总和(Leetcode 124)感到困惑.我找到了一个简单有效的java解决方案,但没有变量获取函数helper()的返回值.为什么它仍然有效?

这是代码:

 public class Solution {

    int max = 0;
    public int maxPathSum(TreeNode root) {
        if(root == null) return 0;
        max = root.val;
        helper(root);
        return max;
    }
    public int helper(TreeNode node)
    {
        if(node == null) return 0;
        int left = helper(node.left);
        int right = helper(node.right);
        left = left > 0 ? left : 0;
        right = right > 0 ? right : 0;
        int curMax = node.val + left + right;
        max = Math.max(max, curMax);
        return node.val + Math.max(left, right);
    }
}
Run Code Online (Sandbox Code Playgroud)

在"maxPathSum()"函数中,第三行,其中是"helper(root)"的返回值?(下面的helper()的定义有一个return语句.)

Tim*_*sen 5

您似乎对返回值的Java方法的概念感到困惑,并且在调用该方法的代码中使用该返回值的义务.即使helper()确实返回了一个值,也没有合同说你必须在调用时也这样做.所以当你打电话

helper(root)
Run Code Online (Sandbox Code Playgroud)

返回值不会在调用它的方法中使用.需要明确的是,呼叫helper(root)并不意味着你会从目前的调用方法执行返回.