LeetCode #124 Binary Tree Maximum Path Sum
2015-08-10 11:02
369 查看
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,
Return
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) { if(root == NULL) return 0; int res = root->val; getMax(root, res); return res; } int getMax(TreeNode *root, int &res){ if(root == NULL) return 0; int left = getMax(root->left,res); int right = getMax(root->right, res); res = max(res, left + right + root->val); return max(0, max(left, right) + root->val); } };
相关文章推荐
- SQL
- 解决ADB关于Please ensure that adb is correctly located at 'D:\..."错误
- Eqs - poj 1840(hash)
- java缓存的使用
- [翻译]写给精明Java开发者的测试技巧
- jQuery基于ajax实现带动画效果无刷新柱状图投票代码
- 关于spring文件上传的配置
- 名字的漂亮度
- 保持业务数据同步
- PreferenceActivity 学习
- 软盘问题
- 五种主要多核并行编程方法分析与比较
- poj 1947(树形背包问题)
- hdu1728 逃离迷宫 【bfs记录转向次数 2种】
- 后台调用js,给同一个事件绑定一个方法
- HDU 3853 LOOPS 可能性dp(水
- Python内置类型——list
- 解决MySQL查询不区分大小写
- Android主线程到底是什么(二)
- WinForm容器内控件批量效验是否允许为空?设置是否只读?设置是否可用等方法分享