【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)); } };
分类:
cpp刷Leetcode
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?