Given a non-empty binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.
Example 1:
Input: [1,2,3]
1
/ \
2 3
Output: 6
Example 2:
Input: [-10,9,20,null,null,15,7]
-10
/ \
9 20
/ \
15 7
Output: 42
image.png
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxPathSum(TreeNode root) {
if (root == null) {
return Integer.MIN_VALUE;
}
int[] maxSum = { Integer.MIN_VALUE };
maxPathSumHelper (root, maxSum);
return maxSum [0];
}
private int maxPathSumHelper (TreeNode root, int[] maxSum) {
if (root == null) {
return 0;
}
// 如果得到的max是负数,那么对于求maxSum没有贡献,直接忽略,取成0
int leftMax = Math.max (maxPathSumHelper (root.left, maxSum), 0);
int rightMax = Math.max (maxPathSumHelper (root.right, maxSum), 0);
int currentMax = root.val + leftMax + rightMax;
// update maxSum
maxSum [0] = Math.max (maxSum[0], currentMax);
// return a path containning root node and make max path sum
return root.val + Math.max (leftMax, rightMax);
}
}