您的位置:首页 > 其它

leetcode: Binary Tree Maximum Path Sum

2015-09-02 17:24 246 查看
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
.

/**
* 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 max_sum=INT_MIN;
int f(TreeNode*root)
{
if(!root)
{
return 0;
}
int left=f(root->left);
int right=f(root->right);
int sum=root->val;
if(left>0)
{
sum+=left;
}
if(right>0)
{
sum+=right;
}
max_sum=max(sum,max_sum);
if(max(left,right)>0)
{
return max(left,right)+root->val;
}
else
{
return root->val;
}
}

int maxPathSum(TreeNode *root)
{
if(!root)
{
return 0;
}
f(root);
return max_sum;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: