-
Notifications
You must be signed in to change notification settings - Fork 257
/
unique-binary-search-trees-ii.cpp
60 lines (53 loc) · 1.5 KB
/
unique-binary-search-trees-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
56
57
58
59
60
// Time: O(n * 4^n / n^(3/2)) ~= Catalan numbers
// Space: O(n)
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @paramn n: An integer
* @return: A list of root
*/
vector<TreeNode *> generateTrees(int n) {
return generateTrees(1, n);
}
vector<TreeNode *> generateTrees(int start, int end) {
vector<TreeNode *> output;
if (start > end) {
output.emplace_back(nullptr);
return output;
}
for (int i = start; i <= end; i++) {
vector<TreeNode *> leftSubTrees = generateTrees(start, i - 1);
vector<TreeNode *> rightSubTrees = generateTrees(i + 1, end);
for (const auto& left : leftSubTrees) {
for (const auto& right : rightSubTrees) {
TreeNode *root = new TreeNode(i);
root->left = clone(left);
root->right = clone(right);
output.emplace_back(root);
}
}
}
return output;
}
TreeNode *clone(TreeNode *root) {
TreeNode *newRoot = nullptr;
if (root) {
newRoot = new TreeNode(root->val);
newRoot->left = clone(root->left);
newRoot->right = clone(root->right);
}
return newRoot;
}
};