对于每一节点,考虑从其左/右子树中的一点到这一个节点的路径所能形成的最大值。Math.max(left.val, right.val) + root.val,是经过这个节点为止的能形成的最大值的一条支路。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
int maxSum = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
if(root == null)
return 0;
getMaxSumWithCurNode(root);
return maxSum;
}
int getMaxSumWithCurNode(TreeNode curNode){
int lmax = 0, rmax = 0;
int value = curNode.val; // 包含当前节点的最大路径和
if(curNode.left != null){
lmax = getMaxSumWithCurNode(curNode.left);
}
if(curNode.right != null){
rmax = getMaxSumWithCurNode(curNode.right);
}
value = value + (lmax>0?lmax:0) + (rmax>0?rmax:0) ;
if(value > maxSum)
maxSum = value;
// 注意这里的返回值,取左右子树其中一条路径
return curNode.val+Math.max( lmax>0?lmax:0, rmax>0?rmax:0 );
}
}