Skip to content

Instantly share code, notes, and snippets.

@safeng
Created May 16, 2014 02:39
Show Gist options
  • Save safeng/17ab40bc469a09a70c66 to your computer and use it in GitHub Desktop.
Save safeng/17ab40bc469a09a70c66 to your computer and use it in GitHub Desktop.
Unique Binary Search Trees II
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void _genBST(int start, int end, vector<TreeNode *> &res)
{
if(start > end)
{
res.push_back(NULL);
return;
}
else
{
for(int i = start; i<=end; ++i)
{
vector<TreeNode *> lres, rres;
_genBST(start, i-1, lres);
_genBST(i+1, end, rres);
// generate all combinations
for(int j = 0; j<lres.size(); ++j)
for(int k = 0; k<rres.size(); ++k)
{
TreeNode * root = new TreeNode(i);
root->left = lres[j];
root->right = rres[k];
res.push_back(root);
}
}
}
}
vector<TreeNode *> generateTrees(int n) {
// Get all. Use recursion
vector<TreeNode *> res;
_genBST(1,n,res);
return res;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment