题目描述:
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
思路:在1~n中选一个数作为根,小于它的数位于左子树,大于它的数位于右子树
递归实现
vector<TreeNode*> DFS (int low, int high)
{vector<TreeNode*> res;
if (low>high)
{
res.push_back(NULL);
return res;
}
for (int i=low; i<=high; i++)
{
vector<TreeNode*> tmp1;
vector<TreeNode*> tmp2;
tmp1=DFS(low,i-1);
tmp2=DFS(i+1,high);
for (int j=0; j<tmp1.size(); j++)
{
for (int k=0; k<tmp2.size(); k++)
{
TreeNode* root=new TreeNode(i);
root->left=tmp1[j];
root->right=tmp2[k];
res.push_back(root);
}
}
}
return res;
}
vector<TreeNode*> generateTrees(int n) {
vector<TreeNode*> res;
if (n==0)
return res;
res=DFS(1,n);
return res;
}