---
# System prepended metadata

title: 'Unique Binary Search Trees II <img src="https://img.shields.io/badge/-easy-brightgreen">'
tags: [data_structure_python]

---

---
tags: data_structure_python
---

# Unique Binary Search Trees II <img src="https://img.shields.io/badge/-easy-brightgreen">

Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ... n.

**Example:**

```
Input: 3
Output:
[
  [1,null,3,2],
  [3,2,null,1],
  [3,1,null,null,2],
  [2,1,3],
  [1,null,2,null,3]
]
Explanation:
The above output corresponds to the 5 unique BST's shown below:

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3
```
 
**Constraints:**

- 0 <= n <= 8

# Solution

### Solution 1: Recursive solution

```python=
# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def generateTrees(self, n: int) -> List[TreeNode]:
        return self.generate(0, n) if n else []

    def generate(self, l, r):
        if l == r:
            return [None]
        else:
            nodes = []
            for i in range(l, r):
                left = self.generate(l, i)
                right = self.generate(i+1, r)

                for lchild in left:
                    for rchild in right:
                        node = TreeNode(i+1)   
                        node.left = lchild
                        node.right = rchild
                        nodes.append(node)
            return nodes

```

### My attempt

```python=
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

class Solution:
    def generateTrees(self, n: int) -> List[TreeNode]:
        L = [i for i in range(1, n+1)]
        self.__generateTrees(L)
        
    def __generateTrees(self, L):
        if L == []:
            return None
        else:
            for i in range(len(L)):
                root = TreeNode(L[i])
                left = self.__generateTrees(L[:i], res)
                right = self.__generateTrees(L[i+1:], res)
                
                for l in left:
                    for r in right:
        
            return res
            
``` 

### Debugging

![](https://cdn.discordapp.com/attachments/432993597625991180/735040423298334760/IMG_20200721_094747.jpg)