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

# Unique Binary Search Trees II

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`

```java
public class Solution {
    public static List<TreeNode> generateTrees(int N) {
        List<TreeNode>[] result = new List[N + 1];
        // result[i] -> stores BSTs with first i nodes
        result[0] = new ArrayList<TreeNode>();
        if (N == 0)
            return result[0];
        // Adding null for calulations later
        result[0].add(null);
        // Starting with 1 node
        for (int n = 1; n <= N; n++) {
            result[n] = new ArrayList<TreeNode>();
            // Consider all the nodes from 1 -> n, as root
            for (int j = 1; j <= n; j++) {
                // Forming all the combinations with different left and right childs
                for (TreeNode nodeL : result[j - 1]) {
                    for (TreeNode nodeR : result[n - j]) {
                        TreeNode node = new TreeNode(j);
                        // The left tree will have correct stucture and values
                        node.left = nodeL;
                        // But the right tree will have correct structure but
                        // but all the values will be offset by "j"
                        node.right = clone(nodeR, j);
                        result[n].add(node);
                    }
                }
            }
        }
        return result[N];
    }

    private static TreeNode clone(TreeNode n, int offset) {
        if (n == null) {
            return null;
        }
        TreeNode node = new TreeNode(n.val + offset);
        node.left = clone(n.left, offset);
        node.right = clone(n.right, offset);
        return node;
    }
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://mayanktyagi3111.gitbook.io/interview-prep/dynamic-programming/unique-binary-search-trees-ii.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
