[leetcode] 124. Binary Tree Maximum Path Sum

Description

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

分析

题目的意思是:
给出一个二叉树,找出节点和最大的路径。

  • 这虽然是一个二叉树遍历的过程,但是结点的值可能为负数,这样我们在计算最大路径值的时候,要注意把求和为负值的分支舍去,保留返回为正值的分支。
  • 递归的代码写得非常的简洁漂亮,这种编程模式在刷题的时候经常看见,最好记住。

C++实现

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    int sum=INT_MIN;
public:
    int maxPathSum(TreeNode* root) {
      preorder(root);
      return sum;
    }
    int preorder(TreeNode* root){
        if(!root){
            return 0;
        }
        int left=max(0,preorder(root->left));
        int right=max(0,preorder(root->right));
        sum=max(sum,root->val+left+right);
        return max(left,right)+root->val;
    }
};

Python实现

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:

    def postorder(self, root):
        if not root:
            return 0
        left_gain = max(self.postorder(root.left),0)
        right_gain = max(self.postorder(root.right),0)
        self.res = max(self.res, left_gain+right_gain+root.val)
        return max(left_gain,right_gain)+root.val

    def maxPathSum(self, root: Optional[TreeNode]) -> int:
        self.res = float('-inf')
        self.postorder(root)
        return self.res

参考文献

[编程题]binary-tree-maximum-path-sum

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

农民小飞侠

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

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

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

打赏作者

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

抵扣说明:

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

余额充值