# 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;
    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jaywin.gitbook.io/leetcode/solutions/0095-unique-binary-search-trees-ii.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
