Python 0894.py
class Solution:
@cache
def allPossibleFBT(self, n: int) -> List[Optional[TreeNode]]:
# each level has an even number of nodes plus there is one root node
# => the total is always odd
if (n & 1) == 0:
return []
if n == 1:
return [ TreeNode() ]
# each subtree has an even number of nodes
result = []
for i in range(1, n, 2):
# all possible trees on the left side
for left in self.allPossibleFBT(i):
remaining = (n - 1) - i
# and all on the right side, obeying the total number of nodes
for right in self.allPossibleFBT(remaining):
# new root node
result.append(TreeNode(0, left, right))
return result
Difficulty
and has an acceptance rate of about 83% (200k+ submissions).
Typical patterns to solve this problem:
- Binary Tree
- Dynamic Programming
- Memoization
- Recursion
- Tree
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation generates every possible full binary tree that contains exactly n nodes. A full binary tree is defined as a tree in which each node has either zero or two children. The algorithm relies on recursion combined with memoization to avoid redundant work, and it systematically explores all ways to partition the node count between left and right subtrees.
Core Logic
The entry point is the method allPossibleFBT. It first checks whether the requested size is feasible. Because a full binary tree must have an odd number of nodes (one root plus an even number of children), the code returns an empty list when n is even. This guard prevents unnecessary recursion for impossible inputs.
if (n & 1) == 0:
return []
When the size is exactly one, the base case is reached. A single node without children satisfies the definition of a full binary tree, so the method returns a list containing a solitary TreeNode instance.
if n == 1:
return [ TreeNode() ]
For larger odd values, the algorithm constructs trees by iterating over all odd splits of the remaining nodes between the left and right subtrees. The loop variable i represents the number of nodes allocated to the left subtree. Because each subtree must also be a full binary tree, i steps through odd numbers from 1 to n - 2. For each split, the method recursively obtains every possible left subtree and every possible right subtree, then combines them under a new root node.
result = []
for i in range(1, n, 2):
for left in self.allPossibleFBT(i):
remaining = (n - 1) - i
for right in self.allPossibleFBT(remaining):
result.append(TreeNode(0, left, right))
return result
The newly created root node is instantiated with a placeholder value (0) and the selected left and right children. All generated trees are collected in the result list, which is returned to the caller.
Edge Cases Handled
The code explicitly addresses two edge conditions.
When n is even, the early return of an empty list acknowledges that no full binary tree can satisfy the node count, eliminating any further processing.
When n equals 1, the method returns a list containing a single node, satisfying the definition of a full binary tree with the minimal possible size. These checks ensure that the recursion always has well-defined termination points.
Performance Optimizations
A notable optimization is the use of the @cache decorator on the allPossibleFBT method. This decorator memoizes the results of each distinct call based on its argument n. Because the recursive process repeatedly requests the same subtree sizes, caching prevents the exponential blow-up that would otherwise occur from recomputing identical subproblems. Each distinct subtree size is computed only once, and subsequent calls retrieve the pre-computed list directly from the cache.
The recursion itself is structured to avoid unnecessary work. By iterating only over odd values of i, the algorithm respects the invariant that both left and right subtrees must contain an odd number of nodes, thereby pruning invalid partitions early. The calculation of remaining as (n - 1) - i ensures that the total node count, including the root, remains consistent throughout the combination step.
Together, memoization and the constrained iteration over valid splits dramatically reduce the number of recursive invocations, making the generation of all possible full binary trees feasible for moderate values of n.
ELI5 - Simplified Explanation
Imagine you want to build special tree houses out of blocks, but these tree houses have a strict rule. Every time you add a new group of blocks to a branch, that branch must split into two smaller branches. Because of this rule, every tree house will always have an odd number of blocks in total.
The code starts by checking if the number of blocks you want to use is even. If it is, the code knows you cannot build this specific type of tree, so it stops and builds nothing.
If you only have one block, the code just makes a single tiny tree house for you.
When you have more blocks, the code gets creative. It picks a number for the left side of the tree, making sure that number is also odd. Then it looks at how many blocks are left over to go on the right side. It finds every single way to build a tree with those left blocks and every way to build a tree with those right blocks. Finally, it takes a new block to act as the roof for the whole thing and connects a left tree and a right tree underneath it. It keeps doing this until it has found every possible pattern you could dream up. The cache part simply helps the code remember the trees it already built so it does not have to do the work twice.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Java | Python | TS | |||||
| WalkCCC | C++ | Java | Python | |||||||
| leetcode.ca | C++ | Java | C# | Rust | Python | Go | TS | |||
| LeetcodeHelp | C++ | Java | Python | |||||||
| Progiez | C++ | Java | Python | |||||||
| github | BigEggStudy | C# | ||||||||
| black-shadows | C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| fartem | Ruby | |||||||||
| fengvyi | C++ | |||||||||
| gouthampradhan | Java | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, C#, Go, Java, Python, Rust, TypeScript | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| Progiez | C++, Java, Python | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| fartem | Ruby | |||||||||
| fengvyi | C++ | |||||||||
| gouthampradhan | Java | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| varunu28 | Java |
Videos
Solved On The Same Day
- problem 1022: Sum of Root To Leaf Binary Numbers
- problem 1582: Special Positions in a Binary Matrix
- problem 2331: Evaluate Boolean Binary Tree
- problem 449: Serialize and Deserialize BST
- problem 919: Complete Binary Tree Inserter
- problem 951: Flip Equivalent Binary Trees
- problem 2415: Reverse Odd Levels of Binary Tree
- problem 297: Serialize and Deserialize Binary Tree
- problem 834: Sum of Distances in Tree
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality