- localMax[n] = max(localMax[n->left] + n->val, localMax[n->right] + n ->val, n->val)
根据左子树和右子树分别return回来的path,我们不断更新最大的Path Sum,时间复杂度O(n),代码如下:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for a binary tree node. | |
* struct TreeNode { | |
* int val; | |
* TreeNode *left; | |
* TreeNode *right; | |
* TreeNode(int x) : val(x), left(NULL), right(NULL) {} | |
* }; | |
*/ | |
class Solution { | |
public: | |
int maxPathSum(TreeNode* root) { | |
int res = INT_MIN; | |
maxPath(root, res); | |
return res; | |
} | |
private: | |
//localMax[i] represents max half path end at node i, localMax[i] = max(localMax[i->left] + i->val, localMax[i->right] + i->val, i->val) | |
int maxPath(TreeNode* root, int& res) | |
{ | |
if(!root)return 0; | |
int left = maxPath(root->left, res), right = maxPath(root->right, res); | |
left = max(0, left); | |
right = max(0, right); | |
res = max(res, left + root->val + right); | |
return max(left, right) + root->val; | |
} | |
}; |
No comments:
Post a Comment