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
.
#include<iostream>
#include<vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
int mymax = INT_MIN;
int maxSum(TreeNode *root) {
if (root==NULL)
return 0;
int leftmax = maxSum(root->left);
int rightmax = maxSum(root->right);
int Value = 0;
if (leftmax>0)
Value+=leftmax;
if (rightmax>0)
Value+=rightmax;
mymax = Value>mymax?Value:mymax;
return max(root->val,max(leftmax+root->val,rightmax+root->val));
}
int maxPathSum(TreeNode *root)
{
if (root==NULL)
return 0;
maxSum(root);
return mymax;
}