参考:http://blog.csdn.net/worldwindjp/article/details/18953987
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.
http://oj.leetcode.com/problems/binary-tree-maximum-path-sum/
解题报告: 返回树中任意两点路径的最大值。只要两点间有路径联通就可以。
需要注意分清最大值和递归函数的返回值。在求值函数里面不能把计算出来的最大值作为返回值返回回去,否则会有问题。
例如对于下面的这个树:
1
/ \
1 -3
/
3
计算到-3节点时,它求出的maxSum(root.left)是3,可以用3更新max,但不能把3作为1的maxSum(root.right)返回给节点1。
如果返回给1的话,会算出最大值为4。
-3节点实际返回给1的是0。
package leetcode.binaryTree;
public class MaximumPathSum {
// 定义了一个属性值,来存放这个最大的值。
private Integer max =Integer.MIN_VALUE;
public MaximumPathSum() {
}
public int maxPathSum(TreeNode root){
if(root == null)
return 0;
int leftMax =0;
int rightMax =0;
int value = root.val;
if(root.left != null){
leftMax= maxPathSum(root.left);
if(leftMax > 0){
value = value + leftMax;
}
}
if(root.right != null){
rightMax = maxPathSum(root.right);
if(rightMax>0){
value = value+ rightMax;
}
}
// 这里的root 是遍历到的每一个节点
// max 存放经过root 和两侧的值
if(value > max)
max = value;
// 经过root节点到单侧的最大的值
return Math.max(root.val, Math.max(root.val + leftMax, root.val + rightMax));
}
public int maximumPathSum(TreeNode root){
if(root == null){
return 0;
}
int maxPath = maxPathSum(root);
return Math.max(max, maxPath);
}
}
测试用例:
package leetcode.binaryTree;
import static org.junit.Assert.*;
import org.junit.Test;
public class MaximumPathSumTest {
@Test
public void testMaximumPathSum() {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(2);
root.right.left = new TreeNode(3);
root.left.right = new TreeNode(3);
root.left.left = new TreeNode(7);
root.left.right.right = new TreeNode(4);
MaximumPathSum mps = new MaximumPathSum();
System.out.println(mps.maximumPathSum(root));
}
}
打印结果为:16