LeetCode124—Binary Tree Maximum Path Sum
来源:互联网 发布:linux重启mysql数据库 编辑:程序博客网 时间:2024/05/01 19:37
LeetCode124—Binary Tree Maximum Path Sum
原题
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 does not need to go through the root.
For example:
Given the below binary tree,1 / \ 2 3
Return 6.
分析
参考:http://blog.csdn.net/linhuanmars/article/details/22969069
这题确实有点难,刚开始以为树的深度遍历序列中找到和最大子序列,这样进行一次深度优先搜索将结果存在数组中,在对数组做一次最大子序列和运算(考虑节点值可能有负数),然而题目的要求并不是这样的。
题目要求是:要在树中找一条连通的通路,其值最大。
对于树中的某个节点来说,需要考虑两件事情:1是记录到该节点时权值是多少(并实时更新最大值),2是记录经过这个节点的路径来自于左孩子还是右孩子,这两件事情一定要分别计算,最大值要算上左右孩子,但是路径只能是左孩子或者右孩子的其中之一。
代码
class Solution { int dfs(TreeNode* root,int &maxSum) { if (root == NULL) return 0; int left = dfs(root->left,maxSum); int right = dfs(root->right,maxSum); int rootval = root->val + max(0, left) + max(0,right); if (maxSum < rootval) maxSum = rootval; // return rootval; return root->val + max(max(left,right),0); }public: int maxPathSum(TreeNode* root) { int maxSum = root->val; dfs(root,maxSum); return maxSum; }};
1 0
- LeetCode124—Binary Tree Maximum Path Sum
- LeetCode124. Binary Tree Maximum Path Sum
- LeetCode124 Binary Tree Maximum Path Sum
- leetcode124~Binary Tree Maximum Path Sum Add to List
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Sublime text 2/3 中 Package Control 的安装与使用方法
- Linux下C语言计算文件的md5值(转)
- 跨平台AR增强现实开发(三)(ARCamera功能与简介)
- 【OpenSSL】SMIME Group Message
- ubuntu定制开机界面系统工具的开发
- LeetCode124—Binary Tree Maximum Path Sum
- Photos.frameWork
- 图像变换 - 图像拉伸、收缩、扭曲、旋转[1] - 仿射变换(cvWarpAffine)
- The auxService:mapreduce_shuffle does not exist 问题解决记录
- SAP模块常用增强总结
- linux下安装Django
- listview使用方法
- location方法详解,获取地址栏URL请求参数,以对象形式保存
- 流行的更换图片的javascript函数集--MM_swapImage函数和MM_swapImgRestore函数