124. Binary Tree Maximum Path Sum

本文探讨了如何在二叉树中寻找具有最大路径和的问题。通过递归算法,我们定义了一个全局变量来存储最大路径值,并在遍历过程中不断更新这个值。文章详细解释了递归函数的设计思路及其实现细节。

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

  1. 问题描述
    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

  2. 解决思路
    定义一个全局变量存储最大值的路径。利用递归,每次递归返回对应节点的最大路径值,在递归中需要更新全部最大值路径。值得注意的是,这里存在负数的情况。。。需要判断一下条件,如果左右子树都返回负数,则递归返回的是该节点的值就好。。。

    1. 代码
/**
 * 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 m;
    int maxPathSum(TreeNode* root) {
        if (!root)
            return 0;
        m = INT_MIN;
        int l_len = helper(root->left);
        int r_len = helper(root->right);
        int count = root->val;
        if (l_len > 0)
            count += l_len;
        if (r_len > 0)
            count += r_len;
        if (count > m)
            m = count;
        return m;
    }
    int helper(TreeNode* root) {
        if (!root)
            return 0;
        if (!root->left && !root->right) {
            if (root->val > m)
                m = root->val;
            return root->val;
        }
        int l_len = helper(root->left);
        int r_len = helper(root->right);
        int count = root->val;
        if (l_len > 0)
            count += l_len;
        if (r_len > 0)
            count += r_len;
        if (count > m)
            m = count;
        if (max(l_len,r_len) >0)
            return max(l_len,r_len)+root->val;
        else
            return root->val;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值