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.
代码语言:javascript复制 1 3 3 2 1
/ / /
3 2 1 1 3 2
/ /
2 1 2 3
求出所有二叉排序数的情况。
每一层枚举中间的点,将小于它的放在左子树,大于的放在右子树,没有元素的子树记得指向NULL。
代码语言:javascript复制/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<TreeNode*> dfs(int l,int r)
{
if(l==r)
{
TreeNode* p=new TreeNode(l);
vector<TreeNode*> now(1,p);
return now;
}
vector<TreeNode*> res;
for(int mid=l;mid<=r;mid )
{
vector<TreeNode*> left,right;
if(l<=mid-1)
left=dfs(l,mid-1);
else
left.push_back(NULL);//开始忘记了
if(mid 1<=r)
right=dfs(mid 1,r);
else
right.push_back(NULL);
for(int i=0;i<left.size();i )
{
for(int j=0;j<right.size();j )
{
TreeNode* p=new TreeNode(mid);
p->left=left[i];
p->right=right[j];
res.push_back(p);
}
}
}
return res;
}
vector<TreeNode*> generateTrees(int n) {
vector<TreeNode*> res,next;
res=dfs(1,n);
return res;
}
};