The trap I meet with C++


  • 4

    dURING my implementation.

    I make one mistake as follows:

        if(s>e)  return NULL;
    
        should be
    
        if(s>e)  return { NULL };
    

    As we will loop left and right result to combine with the root node.

    Here is the AC implementation

    class Solution {
    public:
        vector<TreeNode*> generateTrees(int n) {
            if(n==0)  return vector<TreeNode*>{};
            return help(1, n);
        }
        
        vector<TreeNode*> help(int s, int e){
            vector<TreeNode*> result;
            if(s>e)  return {NULL};
            for(int i=s; i<=e; i++){
                vector<TreeNode*> left=help(s, i-1);
                vector<TreeNode*> right=help(i+1, e);
                for(auto l:left){
                    for(auto r:right){
                        TreeNode* root=new TreeNode(i);
                        root->left=l;
                        root->right=r;
                        result.push_back(root);
                    }
                }
            }
            return result;
        }
    };

  • 0
    Y
    if(s>e) return NULL;
    

    Just curious,you did not get compile error from it? The return type is a vector so the compiler should be able to detect it.

    One more thing, using nullptr instead of NULL.


Log in to reply
 

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