题目:
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 ans;
int maxPathSum(TreeNode *root) {
ans = INT_MIN;
helper(root);
return ans;
}
private:
int helper(TreeNode *root) {
if (root == NULL)
return 0;
int sum = root->val;
int lf = helper(root->left);
int rt = helper(root->right);
if (lf > 0)
sum += lf;
if (rt > 0)
sum += rt;
ans = max(ans, sum);
return max(0, max(lf, rt)) + root->val;
}
};