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 if(n==0) return generate(1,0); 14 return generate(1,n); 15 } 16 17 vector<TreeNode *> generate(int start,int end) 18 { 19 vector<TreeNode *> subtree; 20 if(start>end) 21 { 22 subtree.push_back(NULL); 23 return subtree; 24 25 } 26 27 for(int k=start;k<=end;k++) 28 { 29 vector<TreeNode *> leftsubs=generate(start,k-1); 30 vector<TreeNode *> rightsubs=generate(k+1,end); 31 32 for(auto i:leftsubs) 33 for(auto j:rightsubs) 34 { 35 TreeNode *node=new TreeNode(k); 36 node->left=i; 37 node->right=j; 38 subtree.push_back(node); 39 } 40 } 41 return subtree; 42 } 43 44 45 };