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: n = 5Input: n = 5Split OptionsOutput Trees5 nodesL=1, R=3L=3, R=1Invalid: L=2(even nodes)0000000000Tree 1Tree 2Result: 2 structurally different full binary treesEach node has exactly 0 or 2 childrenRecursively build by splitting nodes between left and right subtrees
Understanding the Visualization
1
Input Validation
Check if n is odd (full binary trees need odd nodes)
2
Split Strategy
Divide remaining n-1 nodes between left and right subtrees
3
Generate Trees
Create all combinations of valid left and right subtrees
Key Takeaway
🎯 Key Insight: Full binary trees require odd number of nodes and can be built by recursively combining all possible left-right subtree pairs
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