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 maxSum=0;
int maxPath(TreeNode *root){
if(root==NULL){
return 0;
}
int left=max(0,maxPath(root->left));
int right=max(0,maxPath(root->right));
maxSum=max(maxSum,left+right+root->val);
return max(left,right)+root->val;
}
int maxPathSum(TreeNode *root) {
if(root==NULL){
return maxSum;
}
maxSum=root->val;
maxPath(root);
return maxSum;
}
};