不多说了~
/**
* 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 maxSumVal = INT_MIN;
currentMaxValue(root,maxSumVal);
return maxSumVal;
}
int currentMaxValue (TreeNode *root,int& sum) {
if(!root){
return 0;
}
int rootSelf = root->val;
int rootLeft = currentMaxValue(root->left,sum);
int rootRight = currentMaxValue(root->right,sum);
int rootLeft2right = rootLeft + rootRight + rootSelf;
int localMaxVal = max(max(rootLeft+rootSelf,rootRight+rootSelft),max(rootLeft+rootSelf,rootSelf));
sum = max(max(sum,localMaxVal),max(sum,rootLeft2right));
return localMaxVal;
}
};