class Solution {
private int maxSum;
public int maxPathSum(TreeNode root) {
if (root == null) return 0;
maxSum = Integer.MIN_VALUE;
helper(root);
return maxSum;
}
private int helper(TreeNode root) {
if (root == null) return 0;
int left_max = helper(root.left);
int right_max = helper(root.right);
int vPathSum = left_max + right_max + root.val;
int currMaxSum = Math.max(left_max, right_max) + root.val;
// 如果两子树最大和都小于零,则从当前node开始重新计算累和
if (currMaxSum < root.val) currMaxSum = root.val;
maxSum = Math.max(maxSum, Math.max(vPathSum, currMaxSum));
return currMaxSum;
}
} class Solution:
def maxPathSum(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def helper(root):
if not root: return 0
left = helper(root.left)
right = helper(root.right)
ret = max(root.val, left + root.val, right + root.val)
self.currMax = max(self.currMax, ret, left + right + root.val)
return ret
self.currMax = float('-inf')
helper(root)
return self.currMax