Learned from http://blog.youkuaiyun.com/lanxu_yy/article/details/17504837. The hard thing about this problem is not how to generate a BST, but how to save the BST when one is generated. The idea here is to declare the vector in every recursion step and save all its left and right subtrees. Let's say I got m left subtrees and n right subtrees, I then generate m*n roots and push all these roots into the vector and return it.
/**
* 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 {
public:
vector<TreeNode*> generateTrees(int n) {
return helper(1,n);
}
vector<TreeNode*> helper(int start,int end)
{
vector<TreeNode*> subtree;
if(start>end)
{
subtree.push_back(NULL);
return subtree;
}
for(int i=start;i<=end;i++)
{
vector<TreeNode*> left=helper(start,i-1);
vector<TreeNode*> right=helper(i+1,end);
for(int j=0;j<left.size();j++)
for(int k=0;k<right.size();k++)
{
TreeNode* root=new TreeNode(i);
root->left=left[j];
root->right=right[k];
subtree.push_back(root);
}
}
return subtree;
}
};