您的位置:首页 > 其它

[leetcode] Binary Tree Maximum Path Sum

2014-08-09 16:08 337 查看
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
.

思路:从底部往顶部搜索,参考链接:http://blog.csdn.net/andrewseu/article/details/28687763

代码:

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