原题链接:https://leetcode-cn.com/problems/unique-binary-search-trees-ii/
此题的思路是对所有n为根节点情况进行遍历,然后对其左右子树进行递归调用,最后将所有节点都保存到vector中即可。
vector<TreeNode*> generateTrees(int n) {
vector<TreeNode*> vtree;
vector<int> vi;
if(n==0) return vtree;
for(int i=1;i<=n;i++) vi.push_back(i);
return recursion(vi,0,n-1);
}
vector<TreeNode*> recursion(vector<int> &v,int start,int end){
vector<TreeNode*> tree;
if(start>end){
tree.push_back(NULL);
return tree;
}
for(int i=start;i<=end;i++){//遍历所有值作为根节点的情况
vector<TreeNode*> left=recursion(v,start,i-1);//对左边进行递归
vector<TreeNode*> right=recursion(v,i+1,end);//对右边进行递归
for(auto x:left){
for(auto y:right){
TreeNode *p=new TreeNode(v[i]);//设置此节点
p->left=x;
p->right=y;
tree.push_back(p);
}
}
}
return tree;
}