【Binary Tree Maximum Path Sum】cpp

题目:

Given a binary tree, find the maximum path sum.

The path may start and end at any node in the tree.

For example:
Given the below binary tree,

       1
      / \
     2   3

 

Return 6.

代码:

复制代码
/**
 * 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_sum = INT_MIN;
            Solution::dfs4MaxSum(root, max_sum);
            return max_sum;
        }
        static int dfs4MaxSum(TreeNode* root, int& max_sum)
        {
            int ret=0;
            if ( !root ) return ret;
            int l = Solution::dfs4MaxSum(root->left, max_sum);
            int r = Solution::dfs4MaxSum(root->right, max_sum);
            if ( l>0 ) ret += l;
            if ( r>0 ) ret += r;
            ret += root->val;
            max_sum = std::max(ret, max_sum);
            return std::max(root->val, std::max(root->val+l, root->val+r));
        }
};
复制代码

tips:

求array最大子序列和是一样的思路。只不过binary tree不是一路,而是分左右两路,自底向上算。

主要注意的地方如下:

1. 维护一个全局最优变量(max_sum),再用ret存放包括前节点在内的局部最大值;每次比较max_sum和ret时,max_sum代表的是不包含当前节点在内的全局最优,ret代表的是一定包含当前节点在内的全局最优。

2. dfs4MaxSum返回时需要注意,left和right只能算一路,不能一起都返到上一层。因为题目中要求的path抻直了只能是一条线,不能带分叉的。

==============================================

第二次过这道题,大体思路有了,细节的错误也都犯了,改过来强化一次AC了。

复制代码
/**
 * 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 ret = INT_MIN;
            if (root) Solution::maxPS(root, ret);
            return ret;
        }
        static int maxPS( TreeNode* root, int& maxSum)
        {
            if ( !root ) return 0;
            int l = Solution::maxPS(root->left, maxSum);
            int r = Solution::maxPS(root->right, maxSum);
            maxSum = max(maxSum, root->val+(l>0?l:0)+(r>0?r:0));
            return max(root->val,root->val+max(r,l));
        }
};
复制代码

 

posted on   承续缘  阅读(159)  评论(0编辑  收藏  举报

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示