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
.
this code is a little bit complicated, I will revise it soon
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#define INVALID_NUM 0xFFFFFFFF
class Solution {
int maxPathSum2(TreeNode *root, int &maxVal)
{
if (root == NULL)
{
return INVALID_NUM;
}
int leftMax = maxPathSum2(root->left, maxVal);
int rightMax = maxPathSum2(root->right, maxVal);
int curMax;
if (leftMax != INVALID_NUM && rightMax != INVALID_NUM)
{
if (leftMax <= 0 && rightMax <=0)
{
curMax = root->val;
}
else if (leftMax <= 0)
{
curMax = root->val+rightMax;
}
else if (rightMax <= 0)
{
curMax = root->val+leftMax;
}
else
{
if (root->val+leftMax >= root->val+rightMax)
{
curMax = root->val+leftMax;
}
else
{
curMax = root->val+rightMax;
}
if (root->val >= curMax)
curMax = root->val;
if (root->val+leftMax+rightMax > maxVal)
{
maxVal = root->val+leftMax+rightMax;
}
return curMax;
}
}
else if (leftMax != INVALID_NUM)
{
if (leftMax <= 0)
{
curMax = root->val;
}
else
{
curMax = root->val+leftMax;
}
}
else if (rightMax != INVALID_NUM)
{
if (rightMax <= 0)
{
curMax = root->val;
}
else
{
curMax = root->val+rightMax;
}
}
else
{
curMax = root->val;
}
if (curMax > maxVal)
maxVal = curMax;
return curMax;
}
public:
int maxPathSum(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() functionr
int maxVal = -10000;
maxPathSum2(root, maxVal);
return maxVal;
}
};