Given n, generate all structurally unique BST's (binary search trees) that store values 1...n.
For example,
Given n = 3, your program should return all 5 unique BST's shown below.
1 3 3 2 1 / / / 3 2 1 1 3 2 / / 2 1 2 3
/** * Definition for binary tree * 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) { if(n==0) { vector<TreeNode *> listTree; TreeNode * root=NULL; listTree.push_back(root); return listTree; } return generate(1,n); } vector<TreeNode*> generate(int l,int r) { vector<TreeNode*> listTree; if(l>r) return listTree; for(int i=l;i<=r;i++) { vector<TreeNode*> left=generate(l,i-1); vector<TreeNode*> right=generate(i+1,r); if(left.size()==0 && right.size()==0) { TreeNode* root=new TreeNode(i); listTree.push_back(root); continue; } if(left.size()==0) { for(int i1=0;i1<right.size();i1++) { TreeNode* root=new TreeNode(i); root->right=right[i1]; listTree.push_back(root); } continue; } if(right.size()==0) { for(int i2=0;i2<left.size();i2++) { TreeNode* root=new TreeNode(i); root->left=left[i2]; listTree.push_back(root); } continue; } for(int i1=0;i1<right.size();i1++) for(int i2=0;i2<left.size();i2++) { TreeNode* root=new TreeNode(i); root->right=right[i1]; root->left=left[i2]; listTree.push_back(root); } } return listTree; } };