> For the complete documentation index, see [llms.txt](https://jaywin.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jaywin.gitbook.io/leetcode/solutions/0095-unique-binary-search-trees-ii.md).

# 0095. Unique Binary Search Trees II

<https://leetcode.com/problems/unique-binary-search-trees-ii>

## Description

Given an integer `n`, return \*all the structurally unique \*\*BST'\**s (binary search trees), which has exactly* `n` *nodes of unique values from* `1` *to* `n`. Return the answer in **any order**.

**Example 1:**

![](https://assets.leetcode.com/uploads/2021/01/18/uniquebstn3.jpg)

```
**Input:** n = 3
**Output:** [[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]]
```

**Example 2:**

```
**Input:** n = 1
**Output:** [[1]]
```

**Constraints:**

* `1 <= n <= 8`

## ac1: divide and conquer

similar: <https://leetcode.com/submissions/detail/147072693/>

```java
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<TreeNode> generateTrees(int n) {
        // Edge cases: n < 1
        if (n < 1) return new ArrayList<>();

        return generate(1, n);
    }

    private List<TreeNode> generate(int start, int end) {
        List<TreeNode> res = new ArrayList<>();
        // Exit
        if (start > end) {
            res.add(null);
        }

        // Iterate
        for (int i = start; i <= end; i++) {
            List<TreeNode> left = generate(start, i-1);
            List<TreeNode> right = generate(i+1, end);
            for (TreeNode l : left) {
                for (TreeNode r : right) {
                    res.add(new TreeNode(i, l, r));
                }
            }
        }

        return res;
    }
}
```

With cache:

```java
class Solution {
    Map<String, List<TreeNode>> cache = new HashMap<>();

    public List<TreeNode> generateTrees(int n) {
        // Edge cases: n < 1
        if (n < 1) return new ArrayList<>();

        return generate(1, n);
    }

    private List<TreeNode> generate(int start, int end) {
        if (cache.containsKey(start + "-" + end)) {
            return cache.get(start + "-" + end);
        }

        List<TreeNode> res = new ArrayList<>();
        // Exit
        if (start > end) {
            res.add(null);
        }

        // Iterate
        for (int i = start; i <= end; i++) {
            List<TreeNode> left = generate(start, i-1);
            List<TreeNode> right = generate(i+1, end);
            for (TreeNode l : left) {
                for (TreeNode r : right) {
                    res.add(new TreeNode(i, l, r));
                }
            }
        }

        cache.put(start + "-" + end, res);
        return res;
    }
}
```
