Unique Binary Search Trees,Unique Binary Search Trees II

时间:2023-03-09 07:06:43
Unique Binary Search Trees,Unique Binary Search Trees II

Unique Binary Search Trees

Total Accepted: 69271 Total Submissions: 191174 Difficulty: Medium

Given n, how many structurally unique BST's (binary search trees) that store values 1...n?

For example,
Given n = 3, there are a total of 5 unique BST's.

   1         3     3      2      1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
class Solution {
public:
int numTrees(int n) {
vector<int> map;
map.push_back();
for (int i = ; i <= n; ++i) {
int t = ;
for (int j = ; j < i; ++j)
t += map[j] * map[i-j-];
map.push_back(t);
}
return map.back();
}
};

Unique Binary Search Trees II

Total Accepted: 45531 Total Submissions: 157430 Difficulty: Medium

Given n, generate all structurally unique BST's (binary search trees) that store values 1...n.

For example,
Given n = 3, your program should return all 5 unique BST's shown below.

   1         3     3      2      1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

/**
* 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 start,int end){
vector<TreeNode*> res;
if(end < start) {
res.push_back(NULL);
return res;
}
for(int rootValue = start; rootValue<=end; ++rootValue){
vector<TreeNode*> left = generateTrees(start,rootValue-);
vector<TreeNode*> right = generateTrees(rootValue+,end);
for(int i=;i<left.size();++i){
for(int j=;j<right.size();++j){
TreeNode *root = new TreeNode(rootValue);
root->left = left[i];
root->right = right[j];
res.push_back(root);
}
}
}
return res;
}
vector<TreeNode*> generateTrees(int n) {
return n== ? vector<TreeNode*>():generateTrees(,n);
}
};