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
Return6.
class Solution {
public:
int maxPathSum(TreeNode *root) {
if(root==NULL)
return 0;
if((root->right==NULL)&&(root->left==NULL)){
return Max=root->val;
}
else{
__maxPathSum(root);
}
return Max;
}
private:
int Max=INT_MIN;
int __maxPathSum(TreeNode *root) {
if(root==NULL)
return 0;
int left=max(0,__maxPathSum(root->left));
int right=max(0,__maxPathSum(root->right));
int re=max(left,right)+root->val;
Max=max(Max,left+right+root->val);
return re;
}
};