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
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<TreeNode*> generateTrees(int n) { 13 vector<TreeNode*> ans; 14 ans=generate(1,n); 15 return ans; 16 } 17 vector<TreeNode*> generate(int a,int b) 18 { 19 vector<TreeNode*> ans; 20 if(a>b) 21 return ans; 22 if(a==b) 23 { 24 TreeNode *temp=new TreeNode(a); 25 ans.push_back(temp); 26 return ans; 27 } 28 vector<TreeNode*> vt1=generate(a+1,b); 29 for(int i=0;i<vt1.size();i++) 30 { 31 TreeNode *tr1=new TreeNode(a);//不能放到外边,否则,ans中的tr1将会变成全部相同一个。(tr1相同,tr1->right不同,故应多分tr1) 32 tr1->right=vt1[i]; 33 ans.push_back(tr1); 34 } 35 36 vector<TreeNode*> vt2=generate(a,b-1); 37 for(int i=0;i<vt2.size();i++) 38 { 39 TreeNode *tr2=new TreeNode(b); 40 tr2->left=vt2[i]; 41 ans.push_back(tr2); 42 } 43 44 for(int i=a+1;i<=b-1;i++) 45 { 46 vector<TreeNode*> vt31=generate(a,i-1); 47 vector<TreeNode*> vt32=generate(i+1,b); 48 for(int j=0;j<vt31.size();j++) 49 { 50 for(int k=0;k<vt32.size();k++) 51 { 52 TreeNode *tr3=new TreeNode(i); 53 tr3->left=vt31[j]; 54 tr3->right=vt32[k]; 55 ans.push_back(tr3); 56 } 57 } 58 59 60 } 61 return ans; 62 } 63 };