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
.
It may contain negative values. So you'll have to deal with it like the biggest subarray sum problem. the idea is exactly the same
/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(!root) return 0;
int maxs=INT_MIN;
get(root, &maxs);
return maxs;
}
int get(TreeNode *root, int * maxs){
if(!root) return 0;
int l=get(root->left,maxs);
int r=get((*root).right,maxs);
if(l+r+root->val>(*maxs)) *maxs=l+r+root->val;
int t=max(l,r);
return t+root->val>0?t+root->val:0;
}
};