所以这是 LeetCode 第 124 题 我使用没有全局变量的 Java,为什么我们需要使用 int[] 或 atomic 但不能使用 int 来存储最大值?我在这里缺乏什么知识?
public int maxGain(TreeNode currNode, int[] res) {
if(currNode == null) { return 0; }
int leftBestSum = Math.max(maxGain(currNode.left, res), 0);
int rightBestSum = Math.max(maxGain(currNode.right, res), 0);
// update best result if it's better to start a new path
int currNodeAndChildSum = currNode.val + leftBestSum + rightBestSum;
// if currSum is better than the best result, start new path
res[0] = Math.max(res[0], currNodeAndChildSum);
// else if currSum is not better than the best result, pass back the best result path to
// its parent for later compare use
int currBestPathSum = currNode.val + Math.max(leftBestSum, rightBestSum);
return currBestPathSum;
}
public int maxPathSum(TreeNode root) {
int[] res = new int[] {Integer.MIN_VALUE};
maxGain(root, res);
return res[0];
}
翻翻过去那场雪
aluckdog
相关分类