/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxPathSum(TreeNode root) {
int[] maxSum = new int[] {Integer.MIN_VALUE};
helper(root, maxSum);
return maxSum[0];
}
private int helper(TreeNode root, int[] maxSum) {
if(root == null) return 0;
int left = Math.max(helper(root.left, maxSum), 0);
int right = Math.max(helper(root.right, maxSum), 0);
maxSum[0] = Math.max(maxSum[0], left + root.val + right);
return root.val + Math.max(left, right);
}
}