-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathall_full_binary_tree.cpp
More file actions
36 lines (34 loc) · 1.05 KB
/
Copy pathall_full_binary_tree.cpp
File metadata and controls
36 lines (34 loc) · 1.05 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
// Problem Link : https://leetcode.com/problems/all-possible-full-binary-trees/
class Solution {
public:
vector<TreeNode*>solve(int n , unordered_map<int , vector<TreeNode*>>&mp){
if(n%2==0){
return {} ;
}
if(n==1){
TreeNode *node = new TreeNode(0) ;
return{node} ;
}
if(mp.find(n)!=mp.end()){
return mp[n] ;
}
vector<TreeNode *>res ;
for(int i =1 ; i<n ; i+=2){
vector<TreeNode *>leftBT = allPossibleFBT(i) ;
vector<TreeNode *>rightBT = allPossibleFBT(n-i-1) ;
for(auto &l : leftBT){
for(auto &r : rightBT){
TreeNode *root = new TreeNode(0) ;
root->left = l ;
root->right=r ;
res.push_back(root) ;
}
}
}
return mp[n]=res ;
}
vector<TreeNode*> allPossibleFBT(int n) {
unordered_map<int , vector<TreeNode*>>mp ;
return solve(n , mp) ;
}
};