All Possible Full Binary Trees - 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. Each element of the answer is the root node of one possible tree. You may return the final list of trees in any order.

A full binary tree is a binary tree where each node has exactly 0 or 2 children.

Input & Output

Example 1 — Small Tree
$ Input: n = 5
Output: [[0,0,0,null,null,0,0],[0,0,0,0,0]]
💡 Note: With 5 nodes, we can create 2 different full binary trees: one with root having left subtree of 1 node and right subtree of 3 nodes, and another with left subtree of 3 nodes and right subtree of 1 node.
Example 2 — Single Node
$ Input: n = 1
Output: [[0]]
💡 Note: Only one possible tree: a single root node with value 0.
Example 3 — Impossible Case
$ Input: n = 4
Output: []
💡 Note: Cannot create a full binary tree with 4 nodes since full binary trees require an odd number of nodes (1 root + even number of children).

Constraints

  • 1 ≤ n ≤ 20
  • n is guaranteed to be odd for non-empty results

Visualization

Tap to expand
All Possible Full Binary Trees INPUT n = 5 Build all full binary trees with exactly 5 nodes Full Binary Tree Rules: Each node has 0 or 2 children All values = 0 n must be odd for valid tree Example Structure: 0 0 0 (n=3 example) ALGORITHM STEPS 1 Base Cases n even --> empty list n=1 --> single node 2 Recursive Split For i=1,3,5... to n-2: left=i nodes, right=n-1-i 3 Combine Subtrees All left x all right combos Create root with children 4 Memoization Cache results by n Avoid recomputation n=5 Splits: i=1: L=1, R=3 i=3: L=3, R=1 Recursively build subtrees then combine all pairs FINAL RESULT 2 Valid Trees Found: Tree 1 0 0 0 0 0 Tree 2 0 0 0 0 0 Output Arrays: [0,0,0,null,null,0,0] [0,0,0,0,0] OK - 2 Trees Both are valid full binary trees with n=5 Time: O(2^n) Catalan Space: O(n * 2^n) with memoization Key Insight: Full binary trees only exist for odd n (each internal node adds 2 children, starting from 1 root). Use recursive decomposition: split n-1 remaining nodes between left and right subtrees in all odd combinations. Memoization avoids recalculating trees for the same subtree sizes. Result count follows Catalan numbers. TutorialsPoint - All Possible Full Binary Trees | Optimal Solution with Memoization
Asked in
Facebook 15 Amazon 12 Google 8 Microsoft 6
89.4K Views
Medium Frequency
~25 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen