<p>Given an integer <code>n</code>, return <em>a list of all possible <strong>full binary trees</strong> with</em> <code>n</code> <em>nodes</em>. Each node of each tree in the answer must have <code>Node.val == 0</code>.</p>

<p>Each element of the answer is the root node of one possible tree. You may return the final list of trees in <strong>any order</strong>.</p>

<p>A <strong>full binary tree</strong> is a binary tree where each node has exactly <code>0</code> or <code>2</code> children.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://s3-lc-upload.s3.amazonaws.com/uploads/2018/08/22/fivetrees.png" style="width: 700px; height: 400px;" />
<pre>
<strong>Input:</strong> n = 7
<strong>Output:</strong> [[0,0,0,null,null,0,0,null,null,0,0],[0,0,0,null,null,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,null,null,null,null,0,0],[0,0,0,0,0,null,null,0,0]]
</pre>

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

<pre>
<strong>Input:</strong> n = 3
<strong>Output:</strong> [[0,0,0]]
</pre>

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

<ul>
	<li><code>1 &lt;= n &lt;= 20</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 allPossibleFBT(self, n: int) -> List[Optional[TreeNode]]:
        #method1: recursive DFS with caching 
        #TC: O(2^n) (weird logic given in editorial)

        #caching needs hashmap (we can add the basecases directly into cache instead of adding in basecase part of our dfs method)
        dp = {0 : [], 1 : [TreeNode()]}

        def dfs(n):
            #basecase (empty tree, only root tree) (given directly in cache hashmap so commented here)
            # if n == 0: 
            #     return []
            # if n == 1:
            #     return [TreeNode()]
            
            #use if present in cache
            if n in dp:
                return dp[n]

            answer = [] #from recursive case we finally wanna give out a list of roots of trees possible
            #recursive-case
            for l in range(n): #0 to n-1
                r = n-l-1 #since l in lefttree and 1 is root so right is total - used 
                leftTreesPossible, rightTreesPossible = dfs(l), dfs(r)

                for leftTree in leftTreesPossible:
                    for rightTree in rightTreesPossible:
                        answer.append(TreeNode(0, leftTree, rightTree))
            
            #save answer in cache for n
            dp[n] = answer

            #return to previous call stack
            return answer

        return dfs(n)
20400