forked from Raushan-Kumar-Sinha/hactoberfest2022-4
-
Notifications
You must be signed in to change notification settings - Fork 0
/
unique_bst_II.cpp
55 lines (53 loc) · 2.15 KB
/
unique_bst_II.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
/**
* 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:
vector<TreeNode*> generateTrees(int n) {
vector<vector<vector<TreeNode*>>> ans(n+1, vector<vector<TreeNode*>>(n+1));
for(int dif = 0; dif < n; dif++) {
for(int i = 1; i <= n-dif; i++) {
if(i == i+dif) {
TreeNode* node = new TreeNode(i);
ans[i][i+dif].push_back(node);
} else {
for(int k = i; k <= i+dif; k++) {
if(i <= k-1 && k+1 <= i+dif) {
for(auto X: ans[i][k-1]) {
for(auto Y: ans[k+1][i+dif]) {
TreeNode* node = new TreeNode(k);
node->left = X;
node->right = Y;
ans[i][i+dif].push_back(node);
}
}
} else if(i > k-1 && k+1 <= i+dif) {
for(auto Y: ans[k+1][i+dif]) {
TreeNode* node = new TreeNode(k);
node->left = NULL;
node->right = Y;
ans[i][i+dif].push_back(node);
}
} else if(i <= k-1 && k+1 > i+dif) {
for(auto X: ans[i][k-1]) {
TreeNode* node = new TreeNode(k);
node->left = X;
node->right = NULL;
ans[i][i+dif].push_back(node);
}
}
}
}
}
}
return ans[1][n];
}
};