Binary Tree Maximum Path Sum
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,
解法:动态规划,对每一个节点,以该节点为根节点的最大值设为value,其左子树的路径最大值为lmax,右子树的路径最大值为rmax,(!!! 注意:这里的lmax和rmax指的是从左/右子节点出发的某一条单向路径,例如对于节点4,lmax=2+3 rmax=6+7+8,而并不是lmax=1+2+3 rmax=5+6+7+8)那么有:
value = value + (lmax>0?lmax:0) + (rmax>0?rmax:0) ;
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.math.*;
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 );
}
}