Leetcode 894. All Possible Full Binary Trees
LeetCode 894: All Possible Full Binary Trees
A full binary tree is a binary tree where each node has exactly 0 or 2 children. 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 with n
nodes must have exactly n
nodes with n being an odd integer, otherwise return an empty list.
To solve this problem, we can use a recursive approach:
n == 1
, return a list with a single node tree because a single node without children is a valid full binary tree.n
nodes:
i
nodes and the right subtree with n-1-i
nodes (since including the root, total nodes are n
).n
to avoid recomputation and thus optimizing the solution.#include <vector>
using namespace std;
// 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 {
public:
vector<TreeNode*> allPossibleFBT(int n) {
if (n % 2 == 0) {
return {}; // No full binary trees possible with even number of nodes
}
// Memoization to store already computed results
static unordered_map<int, vector<TreeNode*>> memo;
// If already computed, return the result from the map
if (memo.find(n) != memo.end()) {
return memo[n];
}
vector<TreeNode*> result;
// Base case: Only one full binary tree possible with 1 node
if (n == 1) {
result.push_back(new TreeNode(0));
memo[n] = result;
return result;
}
// Recursively construct all full binary trees
for (int leftNodes = 1; leftNodes < n; leftNodes += 2) {
int rightNodes = n - 1 - leftNodes;
// Generate left and right subtrees for each valid combination
vector<TreeNode*> leftTrees = allPossibleFBT(leftNodes);
vector<TreeNode*> rightTrees = allPossibleFBT(rightNodes);
// Combine left and right subtrees with the current root
for (auto leftTree : leftTrees) {
for (auto rightTree : rightTrees) {
TreeNode* root = new TreeNode(0);
root.left = leftTree;
root.right = rightTree;
result.push_back(root);
}
}
}
// Store the computed result before returning
memo[n] = result;
return result;
}
};
This solution ensures that all possible full binary trees with n
nodes are generated efficiently using recursive construction and memoization techniques.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?