930. All Possible Full Binary Trees
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to generate all possible full binary trees (FBTs) with a given number of nodes, n. A full binary tree is a special type of binary tree where every node has either 0 or 2 children. All nodes in the tree should have a value of 0.
Solution
All Possible Full Binary Trees in 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:
memo = {}
def allPossibleFBT(self, n: int) -> List[Optional[TreeNode]]:
# Initialize memo for base cases if not already present. Using a class attribute
# for memoization across test cases in some platforms.
if 0 not in Solution.memo:
Solution.memo[0] = []
Solution.memo[1] = [TreeNode(0)]
# Check memoization table first.
if n in Solution.memo:
return Solution.memo[n]
# A full binary tree must have an odd number of nodes.
if n % 2 == 0:
return []
res = []
# Recursively construct trees.
# Iterate through all possible numbers of nodes for the left subtree.
# It must be an odd number (1, 3, 5, ...).
for i in range(1, n, 2):
j = n - 1 - i # Remaining nodes for the right subtree.
# Get all possible left and right subtrees.
left_subtrees = self.allPossibleFBT(i)
right_subtrees = self.allPossibleFBT(j)
# Combine each left subtree with each right subtree.
for left_tree in left_subtrees:
for right_tree in right_subtrees:
root = TreeNode(0, left_tree, right_tree)
res.append(root)
# Store result in memoization table and return.
Solution.memo[n] = res
return res
All Possible Full Binary Trees in Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private Map<Integer, List<TreeNode>> memo = new HashMap<>();
public List<TreeNode> allPossibleFBT(int n) {
// Check memoization table first.
if (memo.containsKey(n)) {
return memo.get(n);
}
// A full binary tree must have an odd number of nodes.
if (n % 2 == 0) {
return new ArrayList<>();
}
List<TreeNode> result = new ArrayList<>();
// Base case: a tree with a single node.
if (n == 1) {
result.add(new TreeNode(0));
} else {
// Recursively construct trees.
// Iterate through all possible numbers of nodes for the left subtree.
// It must be an odd number (1, 3, 5, ...).
for (int i = 1; i < n; i += 2) {
int j = n - 1 - i; // Remaining nodes for the right subtree.
// Get all possible left and right subtrees.
List<TreeNode> leftSubtrees = allPossibleFBT(i);
List<TreeNode> rightSubtrees = allPossibleFBT(j);
// Combine each left subtree with each right subtree.
for (TreeNode leftTree : leftSubtrees) {
for (TreeNode rightTree : rightSubtrees) {
TreeNode root = new TreeNode(0);
root.left = leftTree;
root.right = rightTree;
result.add(root);
}
}
}
}
// Store result in memoization table and return.
memo.put(n, result);
return result;
}
}
All Possible Full Binary Trees in C++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
private:
std::unordered_map<int, std::vector<TreeNode*>> memo;
public:
vector<TreeNode*> allPossibleFBT(int n) {
// Check memoization table first.
if (memo.count(n)) {
return memo[n];
}
// A full binary tree must have an odd number of nodes.
if (n % 2 == 0) {
return {};
}
std::vector<TreeNode*> result;
// Base case: a tree with a single node.
if (n == 1) {
result.push_back(new TreeNode(0));
} else {
// Recursively construct trees.
// Iterate through all possible numbers of nodes for the left subtree.
// It must be an odd number (1, 3, 5, ...).
for (int i = 1; i < n; i += 2) {
int j = n - 1 - i; // Remaining nodes for the right subtree.
// Get all possible left and right subtrees.
std::vector<TreeNode*> left_subtrees = allPossibleFBT(i);
std::vector<TreeNode*> right_subtrees = allPossibleFBT(j);
// Combine each left subtree with each right subtree.
for (TreeNode* left_tree : left_subtrees) {
for (TreeNode* right_tree : right_subtrees) {
TreeNode* root = new TreeNode(0);
root->left = left_tree;
root->right = right_tree;
result.push_back(root);
}
}
}
}
// Store result in memoization table and return.
return memo[n] = result;
}
};
All Possible Full Binary Trees in TypeScript
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
const memo = new Map<number, Array<TreeNode>>();
function allPossibleFBT(n: number): Array<TreeNode | null> {
// Check memoization table first.
if (memo.has(n)) {
return memo.get(n)!;
}
// A full binary tree must have an odd number of nodes.
if (n % 2 === 0) {
return [];
}
const result: Array<TreeNode> = [];
// Base case: a tree with a single node.
if (n === 1) {
result.push(new TreeNode(0));
} else {
// Recursively construct trees.
// Iterate through all possible numbers of nodes for the left subtree.
// It must be an odd number (1, 3, 5, ...).
for (let i = 1; i < n; i += 2) {
const j = n - 1 - i; // Remaining nodes for the right subtree.
// Get all possible left and right subtrees.
const leftSubtrees = allPossibleFBT(i) as TreeNode[];
const rightSubtrees = allPossibleFBT(j) as TreeNode[];
// Combine each left subtree with each right subtree.
for (const leftTree of leftSubtrees) {
for (const rightTree of rightSubtrees) {
const root = new TreeNode(0, leftTree, rightTree);
result.push(root);
}
}
}
}
// Store result in memoization table and return.
memo.set(n, result);
return result;
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.