My 20ms C++ Solution


  • 1
    S

    Other than insert a new node to the old tree of every node. Simply add a delta to the old tree.

    vector<TreeNode*> generateTrees(int n) {
        if(n == 0){
            return {{}};
        }
        vector<vector<TreeNode*> > s(n+1);
        s[0].push_back(nullptr);
        for(int i = 1;i<=n;i++){
            for(int j = 1;j<=i;j++){
                for(int m = 0;m<s[i-j].size();m++){
                    for(int n = 0;n<s[j-1].size();n++){
                        TreeNode *root;
                        root = new TreeNode(j);
                        root->left = s[j-1][n];
                        root->right = createnew(s[i-j][m],j);
                        s[i].push_back(root);
                    }
                    }
            }
        }
        return s[n];
    }
    
    TreeNode * createnew(TreeNode* root,int delta){
        if(!root){
            return nullptr;
        }
        TreeNode * temp;
        temp = new TreeNode(root->val+delta);
        temp->left = createnew(root->left,delta);
        temp->right = createnew(root->right,delta);
        return temp;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.