Skip to content

Commit 4171d29

Browse files
authored
Create all-possible-full-binary-trees.cpp
1 parent 9b6cd2c commit 4171d29

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// Time: O(n * 4^n / n^(3/2)) ~= sum of Catalan numbers from 1 .. N
2+
// Space: O(n * 4^n / n^(3/2)) ~= sum of Catalan numbers from 1 .. N
3+
4+
/**
5+
* Definition for a binary tree node.
6+
* struct TreeNode {
7+
* int val;
8+
* TreeNode *left;
9+
* TreeNode *right;
10+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11+
* };
12+
*/
13+
class Solution {
14+
public:
15+
vector<TreeNode*> allPossibleFBT(int N) {
16+
if (!memo_.count(N)) {
17+
vector<TreeNode*> result;
18+
if (N == 1) {
19+
result.emplace_back(new TreeNode(0));
20+
} else if (N % 2 == 1) {
21+
for (int i = 0; i < N; ++i) {
22+
for (const auto& left: allPossibleFBT(i)) {
23+
for (const auto& right: allPossibleFBT(N - 1 - i)) {
24+
auto node = new TreeNode(0);
25+
node->left = left;
26+
node->right = right;
27+
result.emplace_back(node);
28+
}
29+
}
30+
}
31+
}
32+
memo_[N] = move(result);
33+
}
34+
return memo_[N];
35+
}
36+
37+
private:
38+
unordered_map<int, vector<TreeNode*>> memo_;
39+
};

0 commit comments

Comments
 (0)