码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode – Refresh – Binary Tree Maximum Path Sum

时间:2015-03-18 08:56:01      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:

Use lMax get the maximum value of a sub SINGLE branch (left branch or right branch or just current node).

Use gMax get the maximum value of the whole sub branch (include current node). So gMax need to pass by reference.

 

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int getSum(TreeNode *root, int &gMax) {
13         if (!root) return 0;
14         int lValue = getSum(root->left, gMax), rValue = getSum(root->right, gMax), total = root->val;
15         total += lValue > 0 ? lValue : 0;
16         total += rValue > 0 ? rValue : 0;
17         gMax = max(total, gMax);
18         return max(max(root->val, root->val + lValue), root->val + rValue);
19     }
20     int maxPathSum(TreeNode *root) {
21         int gMax = INT_MIN, lMax = INT_MIN;
22         lMax = getSum(root, gMax);
23         return max(lMax, gMax);
24     }
25 };

 

LeetCode – Refresh – Binary Tree Maximum Path Sum

标签:

原文地址:http://www.cnblogs.com/shuashuashua/p/4346183.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!