> 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.md).

# Unique Binary Search Trees \*

Givenn, how many structurally unique**BST's**(binary search trees) that store values 1...n?

For example,\
Givenn= 3, there are a total of 5 unique BST's.

```
   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3
```

Solution: Let count\[i] be the number of unique binary search trees for i. The number of trees are determined by the number of subtrees which have different root node

F\[0] = 1 ,

F\[1] = 1 , when 1 is root as F\[1] = F\[0] \* F\[0]

F\[2] = F\[0] \* F\[1] when root is 1 then left null and right there are only 1 numbers left

```
      F\[1\]  \* F\[0\] when root is 2 then left contains 1 digits and right is null so.
```

```
class Solution(object):
    def numTrees(self, n):
        if n <= 0:
            return 0
        F = [0] * (n + 1)

        F[0] = 1
        F[1] = 1

        for i in range(2, n + 1):
            for j in range(0, i):
                F[i] += F[j] * F[i - j - 1]
        return F[n]
```
