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
.
这个题不算难,不过有一个陷阱,输入会有负数,这个我一开始没有考虑到.因为负数的关系,这个题里面就不可以随意用零垫底了,要考虑一下细节.
class Solution {
private:
int max(int a, int b)
{
return a > b ? a : b;
}
int searchMax(int &x, TreeNode *root)
{
if(root->left == NULL && root->right == NULL)
{
x = root->val;
return root->val;
}
if(root->left != NULL && root->right != NULL)
{
int a, b = searchMax(a, root->left);
int c, d = searchMax(c, root->right);
x = max(max(a, c), root->val + max(b, 0) + max(d, 0));//这里和下面都以root->val作垫底值
return root->val + max(max(b, d), 0);
}
TreeNode *t = root->left == NULL ? root->right : root->left;
int a, b = searchMax(a, t);
x = max(a, root->val + max(b, 0));
return root->val + max(b, 0);
}
public:
int maxPathSum(TreeNode *root) {
int a;
searchMax(a, root);
return a;
}
};