leetcode 124. Binary Tree Maximum Path Sum

本文介绍了一种高效的算法,用于寻找给定二叉树中节点路径的最大和。算法通过递归方式,考虑每个节点及其左右子树,确保路径至少包含一个节点,且不必经过根节点。通过保存和比较每个节点路径的最大和,最终找到整个二叉树的最大路径和。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a non-empty 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 must contain at least one node and does not need to go through the root.

Example 1:

Input: [1,2,3]

   1
  / \
 2   3

Output: 6
Example 2:

Input: [-10,9,20,null,null,15,7]

   -10
   / \
  9  20
    /  \
   15   7

Output: 42

给出一个二叉树,让输出里面节点路径的最大和,路径可以不包括root,但是必须至少含一个节点

思路:
参照大神的解法
每访问一个节点,记下它自身+left + right的值
然后返回它自身+左右子树中较大的和(只能是左右子树中的一个)
因为返回到上一层的时候,比如example 2的20->15->7的子树,返回到上一层的和只能是20+15或20+7,而不能是20+15+7,那样如果包含-10这个点,就不能算作一个路径了

然后因为之前保存过它自身+left + right的值,所以选这两者中较大的即可找出最大和路径
然后左右子树可以不选,不选即返回0,即返回max(0, left_sum)

//1ms
class Example {
    int ans = Integer.MIN_VALUE;
    
    public int maxPathSum(TreeNode root) {
        if (root == null) {
            return 0;
        }
        
        maxSum(root);
        return ans;
    }
    
    public int maxSum(TreeNode root) {
        if (root == null) {
            return 0;
        }
        
        int left = Math.max(0, maxSum(root.left));
        int right = Math.max(0, maxSum(root.right));
        
        //each time save the max value..
        ans = Math.max(ans, left + right + root.val);
        
        //when return to above level, only one of left and right..
        return Math.max(left, right) + root.val;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值