forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main2.cpp
67 lines (50 loc) · 1.51 KB
/
main2.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
63
64
65
66
67
/// Source : https://leetcode.com/problems/all-possible-full-binary-trees/description/
/// Author : liuyubobobo
/// Time : 2018-08-26
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
/// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
/// Memory Search
/// Time Complexity: O(n^4), Actually, maybe lower than that:)
/// Space Complexity: O(n^4)
class Solution {
private:
TreeNode* root;
public:
vector<TreeNode*> allPossibleFBT(int N){
if(N % 2 == 0)
return {};
unordered_map<int, vector<TreeNode*>> memo;
return allPossibleFBT(N, memo);
}
vector<TreeNode*> allPossibleFBT(int N, unordered_map<int, vector<TreeNode*>>& memo) {
if(memo.find(N) != memo.end())
return memo[N];
if(N == 1)
return memo[1] = {new TreeNode(0)};
for(int i = 1; i < N; i += 2){
vector<TreeNode*> left_vec = allPossibleFBT(i);
vector<TreeNode*> right_vec = allPossibleFBT(N - 1 - i);
for(TreeNode* left: left_vec)
for(TreeNode* right: right_vec){
TreeNode* root = new TreeNode(0);
root->left = left;
root->right = right;
memo[N].push_back(root);
}
}
return memo[N];
}
};
int main() {
Solution().allPossibleFBT(7);
return 0;
}