-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathUnique Binary Search Trees II.cpp
60 lines (43 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
58
59
60
/*
Solution by Rahul Surana
***********************************************************
Given an integer n, return all the structurally unique BST's (binary search trees),
which has exactly n nodes of unique values from 1 to n. Return the answer in any order.
***********************************************************
*/
#include <bits/stdc++.h>
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<TreeNode*> pos(int s, int e){
if(s>e) { return {NULL}; }
if(s==e) { return { new TreeNode(s) }; }
vector<TreeNode*> ans;
for(int i = s; i <= e; i++){
vector<TreeNode*> l = pos(s,i-1);
vector<TreeNode*> r = pos(i+1,e);
for(auto left : l){
for(auto right : r){
TreeNode* x = new TreeNode(i);
x->left = left;
x->right = right;
ans.push_back(x);
}
}
}
return ans;
}
vector<TreeNode*> generateTrees(int n) {
return pos(1,n);
}
};