问题描述:
/**
* 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.
*
*/
找到二叉树的一条路径使这条路径的和最大,这个路径可以从一个点开始也可以从任意一个点结束。
思路就是递归求出左右孩子路径的和,只要此路径的和大于0,那么就可以把这条路径加入到二叉树的最大路径当中。所以可能的情况就是,
1)root
2)root+左边某条路径
3)root+右边某条路径
4)root+左边某条路径+右边某条路径
代码如下:
public class BinaryTreeMaximumPathSum {
private static int max = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
if (root == null) return 0;
maxSum(root);
return max;
}
public static int maxSum(TreeNode root) {
if (root == null) return 0;
int leftVal = maxSum(root.left); //递归求左支路的最大路径和
int rightVal = maxSum(root.right); //递归求右支路的最大路径和
//如果当前局部解(root或left+root或root+right或left+root+right)是最有解,更新最终结果
int curMax = root.val;
if (leftVal > 0) {
curMax += leftVal;
}
if (rightVal > 0) {
curMax += rightVal;
}
if (curMax > max) {
max = curMax;
}
//返回从叶子结点到root的最大路径和(root或left+root或root+right)
return Math.max(root.val, Math.max(root.val + leftVal, root.val + rightVal));
}
//测试代码
public static void main(String arg[])
{
TreeNode r1 = new TreeNode(-3);
TreeNode r2 = new TreeNode(-9);
TreeNode r3 = new TreeNode(20);
TreeNode r4 = new TreeNode(-25);
TreeNode r5 = new TreeNode(7);
TreeNode r6 = new TreeNode(14);
r1.left = r2;
r1.right = r3;
r2.left=r4;
r3.right=r5;
r3.left=r6;
int maxnum=maxSum(r1);
System.out.print(maxnum);
}
}