Welcome to LeetCode Discuss.  Please read the FAQ to help yourself making the best use of Discuss.
Ask a Question
Back to Problem

Welcome to LeetCode Discuss.

This is a place to ask questions related to only OJ problems.

Please read the FAQ to help yourself making the best use of Discuss.

[Run time error]: same code does not have problem with VS9

0 votes
23 views

I got a run time error when input is "1". Here is the code:

class Solution {
public:
    vector<TreeNode *> generateTrees(int n) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        return helper(1,n);
    }
private:
    vector<TreeNode *> helper(int start, int end){
    vector <TreeNode*> results;
    if(start>end)   
    {
        results.push_back(NULL); 
        return results;
    }
    for(int i=start; i<=end; ++i)
    {
        vector <TreeNode*> left=helper(start,i-1); //already includes NULL vector
        vector <TreeNode*> right=helper(i+1,end); //already includes NULL vector
        TreeNode root(i);
        for(int j=0; j<left.size(); ++j)
        {
            for(int k=0; k<right.size(); ++k)
            {
                root.left=left[j];
                root.right=right[k];
                results.push_back(&root);
            }
        }
    }
    return results;     
    }
};
asked 4 days ago in Unique Binary Search Trees II by wshaoxuan (430 points)

1 Answer

+2 votes
 
Best answer

Hey, you are pushing a pointer to a local variable to the vector and this is dangerous because the local variable will be destroyed after you return the vector.

To be specific, the following code will not work properly.

results.push_back(&root);

You have to create the TreeNode dynamically.

class Solution {
public:
    vector<TreeNode *> generateTrees(int n) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        return helper(1,n);
    }
private:
    vector<TreeNode *> helper(int start, int end){
    vector <TreeNode*> results;
    if(start>end)   
    {
        results.push_back(NULL); 
        return results;
    }
    for(int i=start; i<=end; ++i)
    {
        vector <TreeNode*> left=helper(start,i-1); //already includes NULL vector
        vector <TreeNode*> right=helper(i+1,end); //already includes NULL vector
        TreeNode* root;
        for(int j=0; j<left.size(); ++j)
        {
            for(int k=0; k<right.size(); ++k)
            {
                root = new TreeNode(i);
                root->left=left[j];
                root->right=right[k];
                results.push_back(root);
            }
        }
    }
    return results;     
    }
};
answered 2 days ago by porker2008 (1,810 points)
selected 2 days ago by wshaoxuan

...