我仍然对二叉树最大路径和(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);
}
}
在“maxPathSum()”函数中,第三行,“helper(root)”的返回值在哪里? (下面的 helper() 定义有一个 return 语句。)
最佳答案
您似乎对 Java 方法返回值的概念以及在调用该方法的代码中使用该返回值的义务感到困惑。尽管 helper()
确实返回了一个值,但没有契约(Contract)规定您在调用它时必须执行相同的操作。所以当你打电话时
helper(root)
返回值不会在调用它的方法中使用。需要明确的是,调用 helper(root)
并不意味着您将从当前调用方法的执行中返回。
关于java - 为什么这个二分查找成功中间的返回值被忽略了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31644062/