894. All Possible Full Binary Trees

894. All Possible Full Binary Trees

Description

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.

Example 1:

1
2
Input: n = 7
Output: [[0,0,0,null,null,0,0,null,null,0,0],[0,0,0,null,null,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,null,null,null,null,0,0],[0,0,0,0,0,null,null,0,0]]

Example 2:

1
2
Input: n = 3
Output: [[0,0,0]]

Constraints:

  • 1 <= n <= 20

Hints/Notes

  • N/A

Solution

Language: C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
* 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:
map<int, vector<TreeNode*>> m;

vector<TreeNode*> allPossibleFBT(int n) {
vector<TreeNode*> res;
if (n % 2 == 0) {
return res;
}
return build(n);
}

vector<TreeNode*> build(int n) {
if (m.contains(n)) {
return m[n];
}
vector<TreeNode*> res;
if (n == 1) {
res.push_back(new TreeNode(0));
m[n] = res;
return res;
}
for (int i = 1; i < n; i += 2) {
int j = n - i - 1;
auto left = build(i);
auto right = build(j);
for (auto l : left) {
for (auto r : right) {
TreeNode* root = new TreeNode(0);
root->left = l;
root->right = r;
res.push_back(root);
}
}
}
m[n] = res;
return res;
}
};