Given a binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.
For example:
Given the below binary tree,
1 / \ 2 3
Return 6
.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxPathSum(TreeNode* root)
{
maxPath = INT_MIN;
helper(root);
return maxPath;
}
private:
int maxPath;
int helper(TreeNode* root) //返回 包括自己在内的最大值 给上一层节点
{
if (!root->left && !root->right) //左右节点都没有
{
maxPath = max(maxPath, root->val);
return root->val;
}
else if (!root->left && root->right)
{
int rc = helper(root->right);
rc = rc > 0 ? rc : 0;
maxPath = max(maxPath, root->val + rc);
return root->val + rc;
}
else if (root->left && !root->right)
{
int rl = helper(root->left);
rl = rl > 0 ? rl : 0;
maxPath = max(maxPath, root->val + rl);
return root->val + rl;
}
else
{
int rc = helper(root->right);
int lc = helper(root->left);
rc = rc > 0 ? rc : 0;
lc = lc > 0 ? lc : 0;
maxPath = max(maxPath, root->val + rc + lc); //弯曲的情况,当前节点是弯曲点
return root->val + max(rc, lc);
}
}
};