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
.
思路是递归。
每一次的调用中,有三个节点: 当前节点(root),左子节点,右子节点
这样,左子节点(包括它的子节点) + 当前节点 + 右子节点(包括它的子节点) 就可以形成一条path
这条 path 的最大值,就是左子节点调用递归返回的最大值 + 当前节点值 + 右子节点调用递归返回的最大值。 当然,如果左右调用递归返回的最大值小于0,就直接丢弃不用。这样得到的当前最大值就与max进行比较,如果大于max,就更新这个max值。
但是这个方程的返回值不是这个 左中右 三个节点相加得到的当前最大值,因为这个值是作为上一层递归的左路或者右路,这一路不可以有分叉。所以返回值只能是 左节点返回的最大值 + 当前节点
或者是 右节点返回的最大值 + 当前节点
中较大的那个值。
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxHelper(TreeNode root, int[] max) {
if (root == null) {
return 0;
}
// left, mid, right 形成一条 path
// 计算这条 path的最大值,并与 max 比较
int left = maxHelper(root.left, max);
int right = maxHelper(root.right, max);
int sum = ((left < 0) ? 0 : left) + ((right < 0) ? 0 : right) + root.val;
max[0] = Math.max(max[0], sum);
// 计算返回值
// 返回值只能是一条支路上的最大值, 即 left + mid or right + mid,因为不能有分叉
int nextLevelMax = Math.max(left, right);
nextLevelMax = (nextLevelMax < 0) ? 0 : nextLevelMax;
return nextLevelMax + root.val;
}
public int maxPathSum(TreeNode root) {
int[] max = new int[1];
max[0] = Integer.MIN_VALUE;
maxHelper(root, max);
return max[0];
}
}