-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAll_Possible_Full_Binary_Trees.cpp
More file actions
50 lines (42 loc) · 1.19 KB
/
All_Possible_Full_Binary_Trees.cpp
File metadata and controls
50 lines (42 loc) · 1.19 KB
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
// https://leetcode.com/problems/all-possible-full-binary-trees/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
unordered_map < int , vector <TreeNode*> > hash;
vector<TreeNode*> allPossibleFBT(int N)
{
if(hash.count(N) != 0)
return hash[N];
vector < TreeNode * > res;
if(N < 1)
return res;
TreeNode *temp = new TreeNode(0);
if(N == 1)
res.push_back(temp);
for(int i = 1; i < N; i += 2)
{
vector < TreeNode *> left = allPossibleFBT(i);
vector < TreeNode *> right = allPossibleFBT(N-1-i);
for(auto tl : left)
{
for(auto tr : right)
{
TreeNode *tree = new TreeNode(0);
tree->left = tl;
tree->right = tr;
res.push_back(tree);
}
}
}
hash[N] = res;
return res;
}
};