您的位置:首页 > 其它

【LeetCode】Binary Tree Maximum Path Sum

2014-04-21 16:38 411 查看

参考链接

http://blog.csdn.net/aay_dps/article/details/8186372

题目描述


Binary Tree Maximum Path Sum

 

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,
1
/ \
2   3


Return 
6
.

题目分析

找出一条路径和最大的值。

定义F(root) 是i的孩子到i这段路中的最大值。那么F(root) = MAX(root->val,F(root->left),F(root->right))

而过当前结点的最大路径各就是root->val + F(root->left)>0?F(root->left):0+ F(root->right)>0?F(root->right):0

遍历所有结点,就可以求出最大路径和了。

总结

在使用INT_MIN时,不要加一个负数,或减一个正数,否则会溢出。

代码示例

/**
* 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 maxPathSumUtil(TreeNode* root, int& maxLocal)
{
if(root == NULL) return INT_MIN;
int left = maxPathSumUtil(root->left, maxLocal);
int right = maxPathSumUtil(root->right, maxLocal);
int local = root->val;
if(left > 0) local += left;
if(right > 0) local += right;
maxLocal = max(local, maxLocal);
return max(max(left, right), 0)+root->val;
}
int maxPathSum(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(root == NULL) return 0;
int maxLocal = root->val;
maxPathSumUtil(root, maxLocal);
return maxLocal;
}
};

class Solution {
public:
int maxPathSum(TreeNode *root) {
int maxSum = INT_MIN;
maxPathSumHelper(root,maxSum);
return maxSum;
}
int maxPathSumHelper(TreeNode *root, int &maxSum)
{
if(root == NULL)    return INT_MIN;////////////////////后面不能再加负数
int left = maxPathSumHelper(root->left,maxSum);
int right = maxPathSumHelper(root->right,maxSum);
int tmpmax = root->val;
if(left>0) tmpmax+=left;
if(right>0) tmpmax+=right;

maxSum = max(maxSum,tmpmax);

//return max(root->val,max(root->val+left,root->val+right));
return root->val+max(max(left,right),0);
}
};


推荐学习C++的资料

C++标准函数库
http://download.csdn.net/detail/chinasnowwolf/7108919

在线C++API查询
http://www.cplusplus.com/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 二叉树