0311 has seen different

// /**
//  * 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 {
    bool b[40005];
    int l[40005],r[40005],s[40005],ma[40005],mi[40005],n,ans;
    //This function is the index of the storage, the ans as a global variable, either as a parameter, not as a return value, out of the intermediate spare storage space for other values calculated. 
    int Work (the TreeNode * R & lt) 
    { 
        IF (R & lt == nullptr a) return  0 ;
         int X = ++ n-; 
        COUT << " X: " << X << endl; 
        L [X] = Work (R-> left ); 
        R & lt [X] = Work (R-> right);
         // mA [X] = max (R-> Val, max (mA [L [X]], mA [R & lt [X]])); 
        mA [X] = max (R-> Val, max (mA [L [X]], mA [R & lt [X]])); 
        mi The [X] = min (R-> Val, min (mi The [L [X ]], mi The [R & lt [X]])); 
        S [X] = R-> Val + S [L [X]] +S [R & lt [X]]; 
        B [X] = B [L [X]] && B [R & lt [X]] && (mA [L [X]] <R-> Val) && (mi The [R & lt [X] ]> R-> Val);
         iF (B [X]) ANS = max (ANS, S [X]);
         return X; 
    } 
public :
     int maxSumBST (the TreeNode * the root) {
         // BOOL whether BST, the default root subsequent node is expanded to 
        B [ 0 ] = . 1 ; 
        mA [ 0 ] = - 40000 ; 
        mi The [ 0 ] = 40000 ;
         // N-> index, ans-> answer, S [0] 
        n-ANS = S = [ 0 ] = 0  ;
        Work (the root);
        return ans;
        
    }
};
// class Solution {
//     bool b[40005];
//     int l[40005],r[40005],ma[40005],mi[40005],s[40005],n,ans;
//     int work(TreeNode* root)
//     {
//         if(root==nullptr)return 0;
//         int x=++n;
//         l[x]=work(root->left);
//         r[x]=work(root->right);
//         ma[x]=max(root->val,max(ma[l[x]],ma[r[x]]));
//         mi[x]=min(root->val,min(mi[l[x]],mi[r[x]]));
//         s[x]=root->val+s[l[x]]+s[r[x]];
//         b[x]=b[l[x]]&&b[r[x]]&&ma[l[x]]<root->val&&mi[r[x]]>root->val;
//         if(b[x])ans=max(ans,s[x]);
//         return x;
//     }
// public:
//     int maxSumBST(TreeNode* root) {
//         b[0]=1;
//         ma[0]=-40000;
//         mi[0]=40000;
//         n=ans=s[0]=0;
//         work(root);
//         return ans;
//     }
// };

 

Guess you like

Origin www.cnblogs.com/Marigolci/p/12460184.html