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 binary tree public class TreeNode { int val; TreeNode left;
* TreeNode right; TreeNode(int x) { val = x; } }
*/
public class Solution {
public int maxPathSum(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
Max max = new Max();
max.num = root.val;
maxPathSum(root, max);
return max.num;
}
public int maxPathSum(TreeNode node, Max max) {
if (node == null)
return -1;
int currentMax = node.val;
int maxLeft = maxPathSum(node.left, max);
int maxRight = maxPathSum(node.right, max);
if (maxLeft > 0)
currentMax += maxLeft;
if (maxRight > 0)
currentMax += maxRight;
if (currentMax > max.num)
max.num = currentMax;
if (maxLeft > 0) {
if (maxLeft > maxRight) {
return node.val + maxLeft;
} else {
return node.val + maxRight;
}
} else if (maxRight > 0) {
return node.val + maxRight;
} else {
return node.val;
}
}
private class Max {
int num;
}
}