[Leetcode] 124. Binary Tree Maximum Path Sum 解题报告

本文探讨了在二叉树中寻找最大路径和的问题,并详细解释了如何通过深度优先搜索算法来解决这个问题。文章提供了完整的代码实现,展示了如何递归地计算从根节点到每个节点的路径最大和。

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

题目

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

For example:
Given the below binary tree,

       1
      / \
     2   3

Return 6.

思路

这道题目直观上来看,肯定是需要用到深度优先搜索。但是如何巧妙地设计函数参数及返回值却比较关键:由于我们需要得到整个树的sum最大的路径,所以需要有一个变量来维护这个全局sum的最大值。接着对于一个节点root,我们设计函数返回从某个节点到root的路径上的sum的最大值,而这个值和全局最大值有什么关系呢?有了这个值就可以尝试更新全局最大值:计算经过root的sum的最大值,这个值要么只包含root本身,要么包含root的值加上某节点到左子树或者右子树的值,要么包含root的值加上左右子树的值,三者取大就可以了。一旦这三者的最大值大于全局最大值,则更新全局最大值。

代码

/**
 * 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 {
public:
    int maxPathSum(TreeNode* root) {
        int max_value = INT_MIN;
        maxPathSum(root, max_value);
        return max_value;
    }
private:
    int maxPathSum(TreeNode* root, int& max_value) {    // return the max value from some node to the root
        if(root == NULL) {
            return 0;
        }
        int left = maxPathSum(root->left, max_value);
        int right = maxPathSum(root->right, max_value);
        int value = root->val;
        if(left > 0)
            value += left;
        if(right > 0)
            value += right;
        if(max_value < value)
            max_value = value;
        return max(root->val, max(root->val + left, root->val + right));
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值