力扣题95. 不同的二叉搜索树 II
我的问题:
感觉思路没完全错,但是对于分别寻找左右子树的2个for循环不确定这样写对不对;copy函数是为了在原来的搜索树上修改,通过回溯找到新的可行的树,但是这样应该会产生多余的节点没法free掉,感觉这样写不对不知道怎么改。
我的代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
struct TreeNode *copy(struct TreeNode *oldroot)
{
if(oldroot==NULL)
return;
struct TreeNode *newroot=(struct TreeNode*)malloc(sizeof(struct TreeNode));
newroot->val=oldroot->val;
newroot->left=copy(oldroot->left);
newroot->right=copy(oldroot->right);
return newroot;
}
void create(struct TreeNode **res,struct TreeNode *root,int i,int il,int ir,int *res_num,int temp_num,int n)
{
root=(struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val=i;
root->left=root->right=NULL;
temp_num++;
if(temp_num==n)
{
res[++(*res_num)]=copy(res[*res_num]);
return;
}
for(int j=i-1;j>=il;j--)
{
create(res,root->left,j,il,j,res_num,temp_num,n);
}
for(int j=i+1;j<=ir;j++)
{
create(res,root->right,j,j,ir,res_num,temp_num,n);
}
}
struct TreeNode** generateTrees(int n, int* returnSize){
struct TreeNode **res=(struct TreeNode**)malloc(sizeof(struct TreeNode*)*100);
int res_num=0;
int temp_num=0;
int il=1,ir=n;
for(int i=1;i<=n;i++)
{
struct TreeNode* root;
res[res_num]=root;
create(res,root,i,il,ir,&res_num,temp_num,n);
res_num++;
}
*returnSize=res_num;
return res;
}