class Solution {
public:
map<TreeNode*,int>dp1,dp2;
int ans;
void help(TreeNode*x)
{
dp1[x]=dp2[x]=x->val;
if(x->left)
{
help(x->left);
int tmp=dp1[x->left]+(x->val);
//cout<<dp1[x->left]<<" "<<tmp<<endl;
if(tmp>dp1[x]) {dp2[x]=dp1[x];dp1[x]=tmp;}
else if(tmp>dp2[x]) dp2[x]=tmp;
}
if(x->right)
{
help(x->right);
int tmp=dp1[x->right]+(x->val);
//cout<<dp1[x->right]<<" "<<tmp<<endl;
if(tmp>dp1[x]) {dp2[x]=dp1[x];dp1[x]=tmp;}
else if(tmp>dp2[x]) dp2[x]=tmp;
}
ans=max(ans,dp1[x]+dp2[x]-(x->val));
}
int maxPathSum(TreeNode* root) {
if(!root) return 0;
ans=root->val;
dp1.clear();dp2.clear();
help(root);
return ans;
}
};
leetcode 124 【树直径】
最新推荐文章于 2020-09-06 12:45:32 发布