# [95. Unique Binary Search Trees II](https://leetcode.com/problems/unique-binary-search-trees-ii/)
# 思路
题目要求返回由节点1,2,...,n组成的所有二叉搜索树。这题其实是[96. Unique Binary Search Trees](https://leetcode.com/problems/unique-binary-search-trees/)的改版，
思路也是类似的，就是递归的思想，详情见[96题解思路一](https://github.com/ShusenTang/LeetCode/blob/master/solutions/96.%20Unique%20Binary%20Search%20Trees.md)。

我们很容易写出如下代码，但是下面的代码存在一个很严重的问题就是会存在大量的对象拷贝使得运行速度很慢。
所以有了接下来的改进版: 用指针来存储变量。即函数`generateSubTree`是一个指针函数
（关于指针函数，请参考[函数指针与指针函数](http://yulingtianxia.com/blog/2014/04/17/han-shu-zhi-zhen-yu-zhi-zhen-han-shu/)）, 
其返回的不是一个vector，而是指向一个vector的指针。 

> **注意下面两种方式的细微差别，包括初始化和成员函数的访问**


# C++
``` C++
class Solution {
private:
    vector<TreeNode*> generateSubTree(int from, int to){
        vector<TreeNode*>res;
        if(to < from) res.push_back(NULL);
        else if (to == from) res.push_back(new TreeNode(to));
        else{
            for(int i = from; i <= to; i++){
                vector<TreeNode*> left = generateSubTree(from, i - 1);
                vector<TreeNode*> right = generateSubTree(i + 1, to);
                for(int j1 = 0; j1 < left.size(); j1++)
                    for(int j2 = 0; j2 < right.size(); j2++){
                        TreeNode *root = new TreeNode(i);
                        root -> left = left[j1];
                        root -> right = right[j2];
                        res.push_back(root);
                    }
            }
        }
        return res;
    }
public:
    vector<TreeNode*> generateTrees(int n) { 
        if (n == 0) return vector<TreeNode*>(0);
        return generateSubTree(1, n);
    }
};
```
## 改进版*(避免了对象拷贝, 快很多)
``` C++
class Solution {
private:
    vector<TreeNode*> *generateSubTree(int from, int to){
        // 注意这里要让指针res指向某处,而不是vector<TreeNode*> *res;
        vector<TreeNode*> *res = new vector<TreeNode*>();
        if(to < from) res->push_back(NULL); // 或者(*res).push_back(NULL),下同
        else if (to == from) res->push_back(new TreeNode(to));
        else{
            for(int i = from; i <= to; i++){
                vector<TreeNode*> *left = generateSubTree(from, i - 1);
                vector<TreeNode*> *right = generateSubTree(i + 1, to);
                for(int j1 = 0; j1 < left->size(); j1++)
                    for(int j2 = 0; j2 < right->size(); j2++){
                        TreeNode *root = new TreeNode(i);
                        root -> left = (*left)[j1];
                        root -> right = (*right)[j2];
                        res->push_back(root);
                    }
            }
        }
        return res;
    }
public:
    vector<TreeNode*> generateTrees(int n) { 
        if (n == 0) return vector<TreeNode*>(0);
        return *generateSubTree(1, n);
    }
};
```
