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 {
int ant;
public int singleMaximum(TreeNode root){
if(root == null){
return 0;
}
int left = singleMaximum(root.left);
int right = singleMaximum(root.right);
int sum = root.val;
if(left>0){
sum += left;
}
if(right>0){
sum += right;
}
if(sum>ant){
ant = sum;
}
return root.val+Math.max(Math.max(0,left),right);
}
public int maxPathSum(TreeNode root) {
// Note: The Solution object is instantiated only once and is reused by each test case.
ant = Integer.MIN_VALUE;
singleMaximum(root);
return ant;
}
}