> For the complete documentation index, see [llms.txt](https://liuxue2010.gitbook.io/data-structure-and-algorithms/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://liuxue2010.gitbook.io/data-structure-and-algorithms/binary-tree-and-divide-conquer/unique-binary-search-trees-ii.md).

# Unique Binary Search Trees II \*

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

For example,\
Givenn= 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
```

Solution:

```
    if start &gt; end:

        return \[None\]  非常重要，因为如果start &gt; end 说明没有任何所以需要补入Noned的节点进入list 这样才可以补空位。

    常犯的错误，看见start end, 就直接二分法了，应该还是从start 开始一个一个的遍历。
```

double for means Left \* Right

DFS + 分治

```
class Solution(object):
    def generateTrees(self, n):
        """
        :type n: int
        :rtype: List[TreeNode]
        """
        if n <= 0 :
            return []
        return self.dfs(1, n)

    def dfs(self, start, end):
        if start > end: return [None]
        res = []
        for rootval in range(start, end+1):
            LeftTree = self.dfs(start, rootval-1)
            RightTree = self.dfs(rootval+1, end)
            for i in LeftTree:
                for j in RightTree:
                    root = TreeNode(rootval)
                    root.left = i
                    root.right = j
                    res.append(root)
        return res
```
