Binary Tree Maximum Path Sum

406 篇文章 0 订阅
406 篇文章 0 订阅

1,题目要求

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.

在这里插入图片描述
给定非空二叉树,找到最大路径总和。

对于此问题,路径定义为沿着父子连接从树中的某个起始节点到任何节点的任何节点序列。 该路径必须至少包含一个节点,并且不需要通过根节点。

2,题目思路

对于这道题,求一条树中的路径使得加和最大。

一颗树的路径,从一个开始节点出发,向上走0步或者k步,到达某一个根节点,然后再向下走0步或者k步。一旦它往下走,就不会再上升。因此,每条路径都有一个最高节点,其也是这条路径上其他所有节点的最低公共祖先

在对这个问题的解决上,利用递归是比较方便的策略。
在递归的过程中,对于某一个节点,我们会递归地计算它的左子树和右子树的最大的路径之和,然后判断当前节点作为根节点时,路径的值是否是当前所遍历到的所有节点的最大值。
之后,我们返回这个节点作为上升或下降路径的节点的值即可。

3,代码实现

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

static const auto s = []() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    return nullptr;
}();

class Solution {
public:
    int maxPathSum(TreeNode* root) {
        int res = INT_MIN;
        maxPathHelper(root, res);
        return res;
        
    }
private:
    int maxPathHelper(TreeNode* node, int &res){
        if(node == nullptr)
            return 0;
        int left = max(0, maxPathHelper(node->left, res));
        int right= max(0, maxPathHelper(node->right,res));
        
        res = max(res, left + right + node->val);
        return max(left, right) + node->val;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值