FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
LeetCode-Solutions/C++/unique-binary-search-trees-ii.cpp at master · tehsints/LeetCode-Solutions · GitHub
tehsints
/
LeetCode-Solutions
Public
forked from
kamyu104/LeetCode-Solutions
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
LeetCode-Solutions
/
C++
/
unique-binary-search-trees-ii.cpp
Copy path
More file actions
More file actions
Latest commit
History
History
History
57 lines (50 loc) · 1.48 KB
Breadcrumbs
LeetCode-Solutions
/
C++
/
unique-binary-search-trees-ii.cpp
Copy path
File metadata and controls
57 lines (50 loc) · 1.48 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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;
}
};
Back
|
FazBrowse Home
|
New Git URL