-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathAllPossibleBinaryTrees.cpp
62 lines (51 loc) Β· 1.32 KB
/
AllPossibleBinaryTrees.cpp
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
52
53
54
55
56
57
58
59
60
61
62
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
vector<TreeNode*> allPossibleFBT(int n) {
if (n % 2 == 0) {
return {};
}
if (n == 1) {
return { new TreeNode(0) };
}
vector<TreeNode*> result;
for (int i = 1; i < n; i += 2) {
vector<TreeNode*> leftSubtrees = allPossibleFBT(i);
vector<TreeNode*> rightSubtrees = allPossibleFBT(n - 1 - i);
for (TreeNode* left : leftSubtrees) {
for (TreeNode* right : rightSubtrees) {
TreeNode* root = new TreeNode(0);
root->left = left;
root->right = right;
result.push_back(root);
}
}
}
return result;
}
void printTree(TreeNode* root) {
if (root) {
cout << root->val << " ";
printTree(root->left);
printTree(root->right);
} else {
cout << "null ";
}
}
int main() {
int n = 7;
vector<TreeNode*> result = allPossibleFBT(n);
for (TreeNode* root : result) {
printTree(root);
cout << endl;
}
for (TreeNode* root : result) {
delete root;
}
return 0;
}