forked from rui-yan/LeetCode-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
unique-binary-search-trees-ii.cpp
57 lines (50 loc) · 1.48 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
// Time: O(n * 4^n / n^(3/2)) ~= Catalan numbers
// Space: O(n)
/**
* 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:
vector<TreeNode*> generateTrees(int n) {
if (n == 0) {
return {};
}
return generateTreesHelper(1, n);
}
private:
vector<TreeNode *> generateTreesHelper(int start, int end) {
vector<TreeNode *> result;
if (start > end) {
result.emplace_back(nullptr);
return result;
}
for (int i = start; i <= end; ++i) {
vector<TreeNode *> leftSubTrees = generateTreesHelper(start, i - 1);
vector<TreeNode *> rightSubTrees = generateTreesHelper(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);
result.emplace_back(root);
}
}
}
return result;
}
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;
}
};