您的位置:首页 > 其它

Leetcode::Binary Tree Maximum Path Sum

2013-06-28 20:45 369 查看
/**
* Definition for binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#define neg -10000
struct Node
{
int val1;
int val2;
Node():val1(neg),val2(neg){};
};

class Solution {
public:
Node maxPath(TreeNode *root )
{
Node result;

if(root->left == NULL && root->right == NULL)
{
result.val1=result.val2=root->val;
return result;
}
Node LN;
Node RN;

if( root->left != NULL)
{
LN=maxPath(root->left);
}

if( root->right != NULL )
{
RN=maxPath(root->right);
}

int  tmp=max(LN.val1,RN.val1);

if( (root->val >0 || root->val < 0) && tmp < 0)
{
result.val1=root->val;
}
else
{
result.val1=root->val + tmp;
}

result.val2=max(max(max(LN.val2,RN.val2),LN.val1+RN.val1+root->val),result.val1);
return result;
}
int maxPathSum(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
Node result=maxPath(root);

return result.val2;
}

};


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: