您的位置:首页 > 其它

LeetCode – Refresh – Binary Tree Maximum Path Sum

2015-03-18 08:06 441 查看
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.

/**
* 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 getSum(TreeNode *root, int &gMax) {
if (!root) return 0;
int lValue = getSum(root->left, gMax), rValue = getSum(root->right, gMax), total = root->val;
total += lValue > 0 ? lValue : 0;
total += rValue > 0 ? rValue : 0;
gMax = max(total, gMax);
return max(max(root->val, root->val + lValue), root->val + rValue);
}
int maxPathSum(TreeNode *root) {
int gMax = INT_MIN, lMax = INT_MIN;
lMax = getSum(root, gMax);
return max(lMax, gMax);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: