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
.
int maxPathSum(TreeNode *root)
{
if(root == NULL)
{
return 0;
}
if(!root->left && !root->right)
{
return root->val;
}
int value = INT_MIN;
maxPathSumCore(root, value);
return value;
}
int maxPathSumCore(TreeNode *root, int &value)
{
if(root == NULL)
{
return 0;
}
int leftLength = maxPathSumCore(root->left, value);
int rightLength = maxPathSumCore(root->right, value);
int curLength = max(root->val, root->val + max(leftLength, rightLength));
int tempValue = max(curLength, leftLength + rightLength + root->val);
if(tempValue > value)
{
value = tempValue;
}
return curLength;
}