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 maxPathSum(TreeNode *root) {
max = INT_MIN;
buildMaxMap(root);
return max;
}
int buildMaxMap(TreeNode* node)
{
if(node == NULL)
return 0;
int maxL = buildMaxMap(node->left);
int maxR = buildMaxMap(node->right);
int maxNode = std::max(std::max(maxL, maxR) + node->val, node->val);
int curMax = std::max(std::max(maxL + maxR + node->val, node->val), maxNode);
if(curMax > max)
max = curMax;
return maxNode;
}
private:
int max;
};
Round 2:
/**
* 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 maxPathSum(TreeNode *root) {
result = INT_MIN;
helper(root);
return result;
}
private:
int helper(TreeNode *root)
{
if(root == NULL)
return 0;
int left = helper(root->left);
int right = helper(root->right);
int curMax = 0, localMax = 0;
curMax = std::max(std::max(left, right) + root->val, root->val);
localMax = std::max(curMax, left + right + root->val);
if(localMax > result)
result = localMax;
return curMax;
}
int result;
};