Leetcode 124. Binary Tree Maximum Path Sum 最大路径和 解题报告

1 解题思想

在二叉树当中,找到一条路径,这条路径的和最大。

这里所谓的路径,就是每个节点只经过一次的一条路径,可以选择在任何节点开始,也可以选择在任何节点结束

本质上,其有点像用DP的递归方式搜索,因为每个节点只能经过一次,所以对于当前root,最大值可能是:

  • root当前值,左右孩子的值,一共三个值,所有大于0的值的和

但是当 当前root回溯回去,到了其父节点时,root能返回的最值至多包含一个子节点的值。。

嗯,上面可能有些拗口,看代码去吧。。。哈哈,我也讲不清楚。。看着代码好讲些

2 原题

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. 

3 AC解

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    //因为可以不用经过根节点,所以需要记录最大的一个
    private int globalMax = Integer.MIN_VALUE;
    public int maxPathSum(TreeNode root) {
        helper(root);
        return globalMax;
    }
    /**
     *  因为这道题的要求是一个可以到达的路径(图像化理解为:从一边上来,到了最高处后,往下转过去,又是一条折线)也就是说除了某一个节点的位置之外(也就是当前序列深度最小的那一个),其余的位置节点,只能留自己孩子节点里面-》左边或者右边的一个,所以每次需要判断如果当前节点是深度最低的那个,或者自己只是作为其中的一部分,还有更低的节点
     */
    public int helper(TreeNode root) {
        int leftMax = root.left==null?Integer.MIN_VALUE:helper(root.left);
        int rightMax = root.right==null?Integer.MIN_VALUE:helper(root.right);
        // 如果当前位置为转折
        int res = root.val;
        if(leftMax > 0) res += leftMax;
        if(rightMax > 0) res += rightMax;
        globalMax = Math.max(globalMax,res);
        // 如果自己只是作为其中一部分
        return root.val + Math.max(Math.max(0,leftMax),rightMax);
    }
}

最近频繁发生因为leetcode题目测试数据变动而造成的代码不能AC,所以这里特别贴出AC

因为代码完成时间长短不定,所以如果我给的代码不能AC了,请及时评论通知我,我会及时修改的
这里写图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值