# 95. Unique Binary Search Trees II

## 1.問題

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LKRJ5LC-te3_LVD6W6d%2F-LKRMMv6oxM-27mSag7U%2F%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202018-08-21%20%E4%B8%8B%E5%8D%888.02.14.png?alt=media\&token=4092922f-d868-4d3a-8939-c7c1bfa3f687)

## 2.想法

* Recursive
  * Base case
    * 當left > right時, return 空vector
  * Recursive case
    * 二分index: 中間值是root node
    * 再把樹加入vector中
    * 每層vector都是獨立的
* 相關類型
  * merge sort
  * permutation

## 3.程式碼

```
/**
 * Definition for a binary tree node.
 * 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) {
        vector<TreeNode*> ans;
        if (n==0) {
            return ans;
        }
        return generateTrees(1, n);
    }
private:
    vector<TreeNode*> generateTrees(int left, int right) {
        //回傳該層的tree
        //所以只有最上層才會回傳最後結果
        vector<TreeNode*> ans;
        if (left > right) {
            ans.push_back(NULL);
            return ans;
        }
        
        //輪流讓i變成root node
        for (int ii = left; ii <= right; ii++) {
            //兩分: leftTree, righTree兩分到最後, 直到得到leaf
            vector<TreeNode*> leftTree = generateTrees(left, ii - 1);
            vector<TreeNode*> rightTree = generateTrees(ii + 1, right);
            //組合成樹, 返回 
            for (int i = 0; i < leftTree.size(); i++) {
                for (int j = 0; j < rightTree.size(); j++) {
                    //root是i
                    TreeNode* node = new TreeNode(ii);
                    //left
                    node->left = leftTree[i];
                    //right
                    node->right = rightTree[j];
                    ans.push_back(node);
                }    
            }
        }
        return ans;
    }
};
```

## 4.Performance

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LKRJ5LC-te3_LVD6W6d%2F-LKRMUvEY30zZW2TE98D%2F%E8%9E%A2%E5%B9%95%E5%BF%AB%E7%85%A7%202018-08-21%20%E4%B8%8B%E5%8D%888.02.49.png?alt=media\&token=a28a330e-f932-4a99-b55c-393ae7e7522d)
