Leetcode -- Binary Tree Maximum Path Sum
2015-10-24 08:53
447 查看
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,
Return
分析:
此题中dfs返回的值并不是最终结果,只是单方向路径,而最终的最大和在遍历过程中被计算。
在dfs的过程中,以每个节点为中心计算一次sum,保存其最大值,计算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.
/** * 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 maxsum=INT_MIN; int dfs(TreeNode* root) { if(root==NULL) return 0; int left = dfs(root->left); int right = dfs(root->right); int sum = root->val; if(left>0) sum+=left; if(right>0) sum+= right; maxsum = max(maxsum,sum); return max(left,right)>0?max(left,right)+root->val:root->val; } int maxPathSum(TreeNode* root) { dfs(root); return maxsum; } };
分析:
此题中dfs返回的值并不是最终结果,只是单方向路径,而最终的最大和在遍历过程中被计算。
在dfs的过程中,以每个节点为中心计算一次sum,保存其最大值,计算sum的过程中需要左右路径的单方向求和,所以返回此单方向路径和。
相关文章推荐
- 10月小记
- 利用JXL根据Exel的某一列进行拆分Excel
- 第三期RHCA完美收官(含部分学员证书)
- DotNetOpenAuth实践之WebApi资源服务器
- 简单代码复杂化
- 花式秀之Hello world
- vmware 启动虚拟机的时候,报内部错误
- js——点击验证码图片进行刷新验证码
- 避免内存重叠memmove()性能
- WebView的使用
- 开发者必备:微软发布Adobe Photoshop版Win10 UWP通用应用设计模板 [附下载地址]
- android :FTPServer
- 第13章 类继承
- 用KVO实现的监听
- 离线版完美解决eclipse 安装Genymotion插件的安装问题
- 如何让word文档都在同一个窗口下打开 (反之亦可)
- 微软算法100题17 字符串中找到第一个只出现一次的字符
- 3.5 unicodedata--Unicode数据库
- 3.5 unicodedata--Unicode数据库
- 北京,北京