題目:
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
代碼如下:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<TreeNode *> getalltrees(int begin,int end)
{
vector<TreeNode *> result;
if(begin>end)
{
result.push_back(NULL);
return result;
}
vector<TreeNode *> lefttree;
vector<TreeNode *> righttree;
for(int i=begin;i<=end;i++)
{
lefttree=getalltrees(begin,i-1);
righttree=getalltrees(i+1,end);
for(int j=0;j<lefttree.size();j++)
{
for(int t=0;t<righttree.size();t++)
{
TreeNode *root=new TreeNode(i+1);
root->left=lefttree[j];
root->right=righttree[t];
result.push_back(root);
}
}
}
return result;
}
vector<TreeNode *> generateTrees(int n) {
vector<TreeNode *> result;
result=getalltrees(0,n-1);
return result;
}
};