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,

       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];
}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值