给出n,生成所有由1...n为节点组成的不同的二叉查找树
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @paramn n: An integer
* @return: A list of root
*/
vector<TreeNode *> createTrees(int start, int end) {
vector<TreeNode *> ret;
if(start > end) {
ret.push_back((TreeNode *)NULL);
return ret;
}
if(start == end) {
TreeNode * node = new TreeNode(start);
ret.push_back(node);
return ret;
}
for(int i = start; i <= end; ++i) {
vector<TreeNode *> left = createTrees(start, i-1);
vector<TreeNode *> right = createTrees(i+1, end);
for(auto lnode : left) {
for(auto rnode : right) {
TreeNode * root = new TreeNode(i);
root->left = lnode;
root->right = rnode;
ret.push_back(root);
}
}
}
return ret;
}
vector<TreeNode *> generateTrees(int n) {
// write your code here
return createTrees(1, n);
}
};