-
Notifications
You must be signed in to change notification settings - Fork 82
/
All Possible Full Binary Trees.cpp
42 lines (40 loc) · 1.2 KB
/
All Possible Full Binary Trees.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
// https://leetcode.com/problems/all-possible-full-binary-trees/
/**
* 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:
unordered_map<int, vector<TreeNode*>> mp;
vector<TreeNode*> allPossibleFBT(int N) {
vector<TreeNode*> ans;
if(N%2==0) return ans;
if(mp[N].size()!=0) return mp[N];
if(N==1){
ans.push_back(new TreeNode);
}
else if(N%2){
for(int i=1;i<N;i+=2){
int l=i, r=N-1-i;
for(auto itl:allPossibleFBT(l)){
for(auto itr:allPossibleFBT(r)){
TreeNode* root=new TreeNode;
root->left=itl;
root->right=itr;
ans.push_back(root);
}
}
}
mp[N]=ans;
return mp[N];
}
return ans;
}
};