Given a binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path does not need to go through the root.
For example:
Given the below binary tree,
1 / \ 2 3
Return 6
.
题目分析:求二叉树中任意两个节点的路径的最大值。想到的是如果求经过某个节点的向下的某个节点的最大值则是F(left)+val+F(right),这时候可以更新最大值,所以可以递归求解,但是如果要求经过这个节点的某条路径,则要么是左子树+当前点,要么是右子树加当前点,或者当前点,因为分支路径要么经过左子树要么经过右子树。
具体代码如下:
private int maxSum=Integer.MIN_VALUE; //用于记录全局搜索的最大值
public int maxPathSum(TreeNode root) {
maxSum=Integer.MIN_VALUE;
if(root==null) return 0;
scanMax(root);
return maxSum;
}
/**
* 通过递归的搜索左右子树,然后计算,包括当前值和左右子树的最大值,更新最大值
* @param 根节点
* @return 包括root在内的左分支,右分支和没有分支的最大值
* */
public int scanMax(TreeNode root)
{
if(root==null) return 0;
int left=scanMax(root.left);
int right=scanMax(root.right);
int val=root.val;
if(left>0) val+=left;
if(right>0) val+=right;
if(val>maxSum) maxSum=val;
return Math.max(root.val, Math.max(root.val+left, root.val+right));
}