from : https://leetcode.com/submissions/detail/36066022/
Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
For example:
Given the below binary tree,
1 / \ 2 3
Return 6
.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private int max = 0;
public int maxPathSum(TreeNode root) {
if (null != root) {
max = root.val;
}
sums(root);
return max;
}
private int sums(TreeNode root) {
if (null == root) {
return 0;
}
int lsum = sums(root.left);
int rsum = sums(root.right);
int sum = root.val;
if (lsum > 0) {
sum += lsum;
}
if (rsum > 0) {
sum += rsum;
}
if (sum > max) {
max = sum;
}
// as a child, return (root.val+left) or (root.val+right)
int off = 0;
if (lsum > 0 && rsum > 0) {
off = lsum < rsum ? lsum : rsum;
}
return sum - off;
}
}