<p>Given an integer <code>n</code>, return <em>all the structurally unique <strong>BST&#39;</strong>s (binary search trees), which has exactly </em><code>n</code><em> nodes of unique values from</em> <code>1</code> <em>to</em> <code>n</code>. Return the answer in <strong>any order</strong>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/01/18/uniquebstn3.jpg" style="width: 600px; height: 148px;" />
<pre>
<strong>Input:</strong> n = 3
<strong>Output:</strong> [[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]]
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> n = 1
<strong>Output:</strong> [[1]]
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= n &lt;= 8</code></li>
</ul>

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def generateTrees(self, n: int) -> List[Optional[TreeNode]]:
        all_unique = {0: [None], 1: [TreeNode(val=1)]}

        def gen(n):
            if n in all_unique:
                return all_unique[n]

            trees = []

            for left_size in range(0, n):
                left_unique_trees = gen(left_size)
                right_unique_trees = gen(n-1-left_size)

                for tree_a in left_unique_trees:
                    for tree_b in right_unique_trees:
                        trees.append(TreeNode(val=0, left=tree_a, right=tree_b))
            all_unique[n] = trees
            return trees
        
        def refurbish(tree, offset):
            if tree == None:
                return [tree, 0]

            new_left, left_size = refurbish(tree.left, offset)
            new_right, right_size = refurbish(tree.right, offset+left_size+1)
            return [TreeNode(val=left_size+1+offset, left=new_left, right=new_right), left_size+right_size+1]

        return [refurbish(x, 0)[0] for x in gen(n)]
18400