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
int maxLocalMax = root->val;//0 is not correct for all negative values
int maxSum = DFS(root, maxLocalMax);
return max(maxSum, maxLocalMax);
}
int DFS( TreeNode * root, int& maxLocalMax )
{
if(root == NULL)
return 0;
int left = DFS(root->left, maxLocalMax);
int right = DFS(root->right, maxLocalMax);
int localMax = root->val;
if(left > 0)
localMax += left;
if(right > 0)
localMax += right;
maxLocalMax = max(localMax, maxLocalMax);//record the max local max
return max(root->val, max(root->val+left, root->val+right));//return the sum max
}
};
second time
/**
* 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 maxPathSumUtil(TreeNode* root, int& maxLocal)
{
if(root == NULL) return INT_MIN;
int left = maxPathSumUtil(root->left, maxLocal);
int right = maxPathSumUtil(root->right, maxLocal);
int local = root->val;
if(left > 0) local += left;
if(right > 0) local += right;
maxLocal = max(local, maxLocal);
return max(max(left, right), 0)+root->val;
}
int maxPathSum(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(root == NULL) return 0;
int maxLocal = root->val;
maxPathSumUtil(root, maxLocal);
return maxLocal;
}
};
545

被折叠的 条评论
为什么被折叠?



