Given an integer 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
class Solution {
public:
vector<TreeNode*> generateTrees(int n) {
vector<TreeNode*> res;
if(n < 1) return res;
return generate(1, n);
}
vector<TreeNode*> generate(int left, int right){
vector<TreeNode*> ret;
if(left > right) ret.push_back(NULL);
if(left == right) ret.push_back(new TreeNode(left));
if(left < right){
vector<TreeNode*> left_sub, right_sub;
for(int i = left; i<=right; i++){
left_sub = generate(left, i-1);
right_sub = generate(i+1, right);
for(int j = 0; j<left_sub.size(); j++)
for(int k = 0; k<right_sub.size(); k++){
TreeNode* tmp = new TreeNode(i);
tmp -> left = left_sub[j];
tmp -> right = right_sub[k];
ret.push_back(tmp);
}
}
}
return ret;
}
};
网友评论