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 {
static int max = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
max = Integer.MIN_VALUE;
PathSum(root);
return max;
}
public int PathSum(TreeNode root) {
if(root==null) return 0;
int leftmaxsum=0;
int rightmaxsum=0;
int temp=root.val;
if(root.left!=null){
leftmaxsum=Math.max(PathSum(root.left),0);
}
if(root.right!=null){
rightmaxsum=Math.max(PathSum(root.right),0);
}
temp=root.val+leftmaxsum+rightmaxsum;
max=max>temp?max:temp;
return Math.max(root.val,Math.max(root.val+leftmaxsum, root.val+rightmaxsum));
}
}LeetCode 124 Binary Tree Maximum Path Sum
原文地址:http://blog.csdn.net/mlweixiao/article/details/41042067