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
Solution:
vector<TreeNode *> generate(int start, int end)
{
vector<TreeNode *> result;
if(start>end)
{
result.push_back(NULL);
return result;
}
for(int i=start;i<=end;i++)
{
vector<TreeNode *> leftsub = generate(start, i-1);
vector<TreeNode *> rightsub = generate(i+1,end);
for(int m=0;m<leftsub.size();m++)
{
for(int n=0;n<rightsub.size();n++)
{
TreeNode* root = new TreeNode(i);
root->left = leftsub[m];
root->right = rightsub[n];
result.push_back(root);
}
}
}
return result;
}
vector<TreeNode *> generateTrees(int n) {
if(n==0)
{
vector<TreeNode *> result;
result.push_back(NULL);
return result;
}
return generate(1, n);
}
No comments:
Post a Comment