-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0095-unique-binary-search-trees-ii.cpp
More file actions
44 lines (43 loc) · 1.3 KB
/
0095-unique-binary-search-trees-ii.cpp
File metadata and controls
44 lines (43 loc) · 1.3 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
37
38
39
40
41
42
43
44
/**
* 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 {
private:
vector<TreeNode*> ans;
void genTrees(int minVal, int maxVal, vector<TreeNode*>& trees) {
for (int rootVal = minVal; rootVal <= maxVal; ++rootVal) {
vector<TreeNode*> leftTrees;
vector<TreeNode*> rightTrees;
if (minVal <= rootVal - 1) {
genTrees(minVal, rootVal - 1, leftTrees);
} else {
leftTrees.push_back(NULL);
}
if (rootVal + 1 <= maxVal) {
genTrees(rootVal + 1, maxVal, rightTrees);
} else {
rightTrees.push_back(NULL);
}
for (int i = 0; i < leftTrees.size(); ++i) {
for (int j = 0; j < rightTrees.size(); ++j) {
TreeNode* newTree = new TreeNode(rootVal);
newTree->left = leftTrees[i];
newTree->right = rightTrees[j];
trees.push_back(newTree);
}
}
}
}
public:
vector<TreeNode*> generateTrees(int n) {
ans.clear();
genTrees(1, n, ans);
return ans;
}
};