-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathUnique_Binary_Search_Trees_II.cpp
39 lines (38 loc) · 1.22 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
/**
* 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 {
void generateTreesUtil(int left, int right, vector<TreeNode*>& result) {
if(left > right) {
result.push_back(nullptr);
return;
}
for(int i = left; i <= right; i++) {
vector<TreeNode*> leftSubTrees;
generateTreesUtil(left, i - 1, leftSubTrees);
vector<TreeNode*> rightSubTrees;
generateTreesUtil(i + 1, right, rightSubTrees);
for(TreeNode* leftSubTree : leftSubTrees) {
for(TreeNode* rightSubTree : rightSubTrees) {
TreeNode* root = new TreeNode(i);
root->left = leftSubTree;
root->right = rightSubTree;
result.push_back(root);
}
}
}
}
public:
vector<TreeNode*> generateTrees(int n) {
vector<TreeNode*> result;
if(n == 0) return result;
generateTreesUtil(1, n, result);
return result;
}
};