题目: 给定一个非空二叉树,返回其最大路径和。 本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。
输入: [-10,9,20,null,null,15,7] 输出: 42
-10
/ \
9 20
/ \
15 7
class Solution {
int ans = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
if (root == null) return 0;
helper(root);
return ans;
}
// 这个方法返回的只是root作为路径端点时的最长路径和
// 实际上,root会遍历到每个节点,那么在遍历到这些节点的时候,比较更新ans
// ans跟return 的路径和是分开的
// ans的更新 是依据 helper返回值,所以调研方法里没有直接返回helper
int helper(TreeNode root) {
//通过后序遍历的方式,先计算出左右子树的最大路径和,然后再计算当前树的最大路径和
if (root == null) return 0;
// 左边能支撑的最大路径和,和 0相比,
//0的意义是:root作为路径端点,不加入左路径,那么左边路径提高的路径和就是0
int leftPathSum = Math.max(helper(root.left), 0);
int rightPathSum = Math.max(helper(root.right), 0);
// 更新ans, 当前节点必须在路径中时得到一条路径和,和ans比较
// 比如示例2中root=20,得到的就是root.val+leftPathSum+rightPathSum
// 就是 20+15+7=42,
// 以后在回溯到root=-10 时,得到的root.val+leftPathSum+rightPathSum
//就是-10+9+35=34
// 但是显然34 < 此时的ans=42; ans保持不变
ans = Math.max(ans, root.val + leftPathSum + rightPathSum);
return root.val + Math.max(leftPathSum, rightPathSum);
}
}