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.
public class Solution {
int maxvalue = Integer.MIN_VALUE;
public int getMaxSum(TreeNode root){
int maxleft=0;
int maxright=0;
if(root.left!=null){
maxleft = getMaxSum(root.left);
}
if(root.right!=null){
maxright = getMaxSum(root.right);
}
int sum = root.val;
if(maxleft>0){
sum += maxleft;
}
if(maxright>0){
sum +=maxright;
}
maxvalue = Math.max(maxvalue, sum);
return Math.max(maxleft, maxright)>0?Math.max(maxleft, maxright)+root.val:root.val;
}
public int maxPathSum(TreeNode root) {
int value = getMaxSum(root);
value = Math.max(value, maxvalue);
return value;
}
public static void main(String [] args){
Solution solution = new Solution();
TreeNode root = new TreeNode(1);
root.left = new TreeNode(-2);
root.right = new TreeNode(-3);
root.left.left = new TreeNode(1);
root.left.right = new TreeNode(3);
root.left.left = new TreeNode(-1);
root.right.left = new TreeNode(-2);
//root.right.right = new TreeNode(3);
//root.right.right.right = new TreeNode(-2);
System.out.println(solution.maxPathSum(root));
}
}
494

被折叠的 条评论
为什么被折叠?



