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;
}
};