LC124 Binary Tree Maximum Path Sum
这道题一开始就没什么明确的正确想法,大致想着把树深度遍历,然后在遍历路径的上做文章,找到两条路径,这两条路径分别是树中部分结点相加之和第一大和第二大的路径。对这两条路径的头结点找最近公共祖先,然后看看这两条路径相连起来会不会是一个更大的和。找每条路径的基本思路来自求一个数组子数组的最大和题目。但最终感觉这么做下去太复杂了,也未必正确。
正确思路是,从下往上找,然后用一个数记录当前最大和。
1 class Solution { 2 public: 3 int sum; 4 int DFS(TreeNode* root) 5 { 6 int left=0,right=0,val=root->val; 7 if(root->left!=NULL) 8 left=DFS(root->left); 9 if(root->right!=NULL) 10 right=DFS(root->right); 11 if(left>0) 12 val+=left; 13 if(right>0) 14 val+=right; 15 if(val>sum) 16 sum=val; 17 return max(root->val,max(root->val+left,root->val+right)); 18 } 19 int maxPathSum(TreeNode* root) { 20 sum=root->val; 21 DFS(root); 22 return sum; 23 } 24 };
View Code
转载于:https://www.cnblogs.com/vaecn/p/5303842.html
LC124 Binary Tree Maximum Path Sum相关推荐
- Binary Tree Maximum Path Sum
Binary Tree Maximum Path Sum 题目链接:https://leetcode.com/problems... dfs对每个node,查一下包含这个node的最大路径值. /** ...
- 124 Binary Tree Maximum Path Sum
题目: 124 Binary Tree Maximum Path Sum 这道题就是分别算出左子树和右子树的可能最大和,然后对Path的值进行更新即可 class Solution:def __ini ...
- 【LeetCode】124. Binary Tree Maximum Path Sum
Binary Tree Maximum Path Sum Given a binary tree, find the maximum path sum. The path may start and ...
- 【重点】LeetCode 124. Binary Tree Maximum Path Sum
LeetCode 124. Binary Tree Maximum Path Sum 参考链接:http://zxi.mytechroad.com/blog/tree/leetcode-124-bin ...
- Leetcode | Binary Tree Maximum Path Sum
Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree. ...
- 124. Binary Tree Maximum Path Sum
题目: Given a binary tree, find the maximum path sum. For this problem, a path is defined as any seque ...
- Leetcode: Binary Tree Maximum Path Sum
Given a binary tree, find the maximum path sum.The path may start and end at any node in the tree.Fo ...
- 【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 tr ...
- [Leetcode] Binary Tree Maximum Path Sum
这是LeetCode上的一道题目,需要求二叉树中两点路径的最大和.原题是 https://oj.leetcode.com/problems/binary-tree-maximum-path-sum/ ...
最新文章
- numpy vsplit
- python 批量读取文件夹的动漫美女图并显示
- docker可视化管理界面_分析一款Docker容器可视化管理工具Porttainer
- 多线程不重复读取数据_别再犯错了,多线程访问同一个资源一定要上锁?
- MCN是啥?了解一下这5个互联网热词
- MongoDB第二天
- 排序算法——归并排序的相关问题
- easyui修改css样式,修改easyui的easyloader的默认css目录路径
- bzoj千题计划290:bzoj3143: [Hnoi2013]游走
- vs2019社区版+qt5.14.2+Coin3D安装
- 计算机装系统常用单词,电脑bios中英文对照表大全,安装系统再也不怕英文了...
- 没有基础怎么学习PLC编程?
- 洛谷试炼场 没了 不见了?
- 计算机课程说课ppt模板,信息技术说课ppt模板
- Word中如何删除分隔符?
- [工具] 小白如何修改解包打包system.img
- 华为鸿蒙系统有没有畅玩7c,华为荣耀畅玩7C有什么新功能
- 关于股票的一些学习书籍
- 太厉害了,终于有人能把云计算、大数据和人工智能一次性讲明白了
- 安卓原生应用开发!一起刷完了这份1307页的安卓面试宝典吧,值得收藏!
热门文章
- 关于Redis缓存,这3个问题一定要知道!
- 跟我学Springboot开发后端管理系统5:数据库读写分离
- 为了面试,从头到尾说一次 Java 垃圾回收
- Kafka为什么这么快?
- 综述:如何给模型加入先验知识
- 腾讯ARC、华中科大联合提出QueryInst,开启基于Query的实例分割新思路
- 两大顶级 AI 算法一起开源!Nature、Science 齐发 Alphafold2 相关重磅,双厨狂喜~...
- 中国最大AI预训练模型发布:113亿参数!北京智源研究院、阿里、清华等联手打造...
- 引燃AI社区,不用跨界也能从文本生成图像,OpenAI新模型打破自然语言与视觉次元壁...
- 看图学NumPy:掌握n维数组基础知识点,看这一篇就够了