All Possible Full Binary Trees — LeetCode 894 Python Solution

MediumTreeRecursionMemoizationDynamic ProgrammingBinary Tree
Problem
#894
Reading time
4 min

The problem

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

Example

Input
n = 7
Output
[[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]]

Python solution

Python
# 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]]:
        @cache
        def dfs(n: int) -> List[Optional[TreeNode]]:
            if n == 1:
                return [TreeNode()]
            ans = []
            for i in range(n - 1):
                j = n - 1 - i
                for left in dfs(i):
                    for right in dfs(j):
                        ans.append(TreeNode(0, left, right))
            return ans

        return dfs(n)

Complexity

MeasureComplexity
TimeO(\frac{2^n}{\sqrt{n}})
SpaceO(\frac{2^n}{\sqrt{n}}) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 894. All Possible Full Binary Trees is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 894. All Possible Full Binary Trees?
LeetCode 894. All Possible Full Binary Trees is rated Medium on LeetCode.
What is the time complexity of LeetCode 894. All Possible Full Binary Trees?
The Python solution on this page runs in O(\frac{2^n}{\sqrt{n}}).
What is the space complexity of LeetCode 894. All Possible Full Binary Trees?
The Python solution on this page uses O(\frac{2^n}{\sqrt{n}}) auxiliary space.
What topics does LeetCode 894. All Possible Full Binary Trees cover?
LeetCode 894. All Possible Full Binary Trees is tagged Tree, Recursion, Memoization, Dynamic Programming and Binary Tree on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview