leetcode: Binary Tree Maximum Path Sum
2015-09-02 17:24
246 查看
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 binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution{ public: int max_sum=INT_MIN; int f(TreeNode*root) { if(!root) { return 0; } int left=f(root->left); int right=f(root->right); int sum=root->val; if(left>0) { sum+=left; } if(right>0) { sum+=right; } max_sum=max(sum,max_sum); if(max(left,right)>0) { return max(left,right)+root->val; } else { return root->val; } } int maxPathSum(TreeNode *root) { if(!root) { return 0; } f(root); return max_sum; } };
相关文章推荐
- Mysql的存储引擎之:MERGE存储引擎
- android如何打印当前的线程及进程
- 继承
- iOS开发~iPhone6及iPhone6P的UI适配
- go-反射机制
- QT项目中的相关知识
- Android 属性动画 (一)
- ARM Linux 3.x的设备树(Device Tree)
- 无线路由器设置
- Swift 设置字体
- Memcached之HA架构(9)
- C# 全角符号转半角
- Oracle中生成随机数的函数
- MFC中改变控件的TAB顺序
- 天猫首页迷思之-jquery实现整个div的懒加载(1)
- 为什么你总是喜欢有夫之妇
- iOS工程使用cocoaPods。动手让你的工程由xcodeproj变身为.xcworkspace
- hdu 2222 Keywords Search ac自动机入门
- 在Visual Studio 2010中开发Qt程序
- 快速排序算法与插入排序算法的结合