您的位置:首页 > 其它

[LeetCode]Binary Tree Maximum Path Sum

2013-05-27 19:15 330 查看
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: