您的位置:首页 > 其它

leetcode 124 【树直径】

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