File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments