/**
* 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 {
private:
vector<TreeNode *> generate(int start,int end)
{
vector <TreeNode *> ret;
if(start>end)
{
return ret;
}
else if(start==end)
{
TreeNode *temp=new TreeNode(start);
ret.push_back(temp);
return ret;
}
else
{
int i=start;
vector<TreeNode*>righttree=generate(i+1,end);
for(vector<TreeNode*>::iterator ir=righttree.begin();ir!=righttree.end();ir++)
{
TreeNode * newroot=new TreeNode(i);
newroot->left=NULL;
newroot->right=*ir;
ret.push_back(newroot);
}
for( i=start+1;i<end;i++)
{
vector<TreeNode*>lefttree=generate(start,i-1);
vector<TreeNode*>righttree=generate(i+1,end);
for(vector<TreeNode*>::iterator il=lefttree.begin();il!=lefttree.end();il++)
{
for(vector<TreeNode*>::iterator ir=righttree.begin();ir!=righttree.end();ir++)
{
TreeNode * newroot=new TreeNode(i);
newroot->left=*il;
newroot->right=*ir;
ret.push_back(newroot);
}
}
}
i=end;
vector<TreeNode*>lefttree=generate(start,i-1);
for(vector<TreeNode*>::iterator il=lefttree.begin();il!=lefttree.end();il++)
{
TreeNode * newroot=new TreeNode(i);
newroot->left=*il;
newroot->right=NULL;
ret.push_back(newroot);
}
return ret;
}
}
public:
vector<TreeNode*> generateTrees(int n) {
vector<TreeNode *>ret=generate(1,n);
return ret;
}
};
95. Unique Binary Search Trees II
最新推荐文章于 2022-01-13 04:43:51 发布