lintcode:Binary Tree Maximum Path Sum
来源:互联网 发布:阿里云ecs 搭建vpn 编辑:程序博客网 时间:2024/05/04 21:44
Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
Example
Given the below binary tree,
1 / \ 2 3
Return 6
.
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */class Solution { private: int max5(int a, int b, int c, int d, int e) { return max(max(max(a, b), max(c, d)), e); } int max3(int a, int b, int c) { return max(max(a, b), c); } int maxPathSumHelper(TreeNode *Node, int &maxSum) { if (Node == NULL) return 0; int leftMax = maxPathSumHelper(Node->left, maxSum); int rightMax = maxPathSumHelper(Node->right, maxSum); maxSum = max5(maxSum, Node->val, Node->val+leftMax, Node->val+rightMax, Node->val+leftMax+rightMax); return max3(Node->val, Node->val+leftMax, Node->val+rightMax); } public: /** * @param root: The root of binary tree. * @return: An integer */ int maxPathSum(TreeNode *root) { // write your code here int maxSum = -10000; int leftMax = maxPathSumHelper(root->left, maxSum); int rightMax = maxPathSumHelper(root->right, maxSum); return max5(maxSum, root->val, leftMax+root->val, rightMax+root->val, leftMax+rightMax+root->val); }};
0 0
- lintcode:Binary Tree Maximum Path Sum
- *[Lintcode]Binary Tree Maximum Path Sum
- [lintcode] Binary Tree Maximum Path Sum II
- Binary Tree Maximum Path Sum ---lintcode
- 20150708 lintcode 总结 Binary Tree Maximum Path Sum Show result *****
- 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
- 新闻系统——SQLHelper助手优化
- 不同环境中的换行符
- Java并发编程:Timer和TimerTask(转载)
- 第十一周项目2 - 职员有薪水了(2、来个深复制)
- istringstream在读文件时候的应用
- lintcode:Binary Tree Maximum Path Sum
- linux 防火墙屏蔽和删除 ip
- 自定义视图控制器容器
- hdu1247Hat’s Words
- MATLAB 几何运算之图像的放大
- poj3581_Sequence(后缀数组)
- poj 2356 Find a multiple (鸽巢原理妙用)
- Java学习资源整理
- 基本数据类型对象包装类的一些理解