Unique Binary Search Trees
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.
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
//Unique Binary Search Trees
class Solution {
unordered_map<int, int> r;
public:
int process(int n){
if (r[n]) return r[n];
int result = 0;
for(int left = 0; left < n; ++left){
result += process(left)*process(n-left-1);
}
r[n] = result;
return result;
}
int numTrees(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
r.clear();
r[0] = 1;
r[1] = 1;
return process(n);
}
};
Unique Binary Search Trees II
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.
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
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
vector<TreeNode* > build(int start, int end){//inclusive
if (start > end) return vector<TreeNode*>(1,(TreeNode*)NULL);
if (start == end) return vector<TreeNode*>(1,new TreeNode(start));
vector<TreeNode* > r;
for(int root_val = start ;root_val <= end; ++root_val){
vector<TreeNode* > r_left = build(start, root_val - 1);
vector<TreeNode* > r_right = build(root_val+1, end);
for(int ii = 0; ii < r_left.size(); ++ii){
for(int jj = 0; jj < r_right.size(); ++jj){
TreeNode* head = new TreeNode(root_val);
head->left = r_left[ii];
head->right = r_right[jj];
r.push_back(head);
}
}
}
return r;
}
public:
vector<TreeNode *> generateTrees(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
return build(1,n);
}
};
No comments:
Post a Comment