i have 2 bsts(binary search trees) they both have common elements (if 1 have 4 for example the other have 4)(that's an explanation) so i want to delete that element for example from one tree not both so can u help me ? if u want need explanation tell me :)) so plz help me :)i tried this code but it is not passing case 1 on hackerrank
What I have tried:
typedef struct node{
int data;
struct node *left, *right;
}*Btree;
int insert(Btree *b, int e){
if (!*b){
*b = (Btree)malloc(sizeof(struct node));
if (!*b) return 0;
(*b)->data = e;
(*b)->right = NULL;
(*b)->left = NULL;
return 1;
}
else
if (e<=(*b)->data)
return insert(&((*b)->left), e);
else
return insert(&((*b)->right), e);
}
Btree min(Btree b){
if (!b)return NULL;
if (b->left)
return min(b->left);
return b;
}
Btree max(Btree b){
if (!b)return NULL;
if (b->right)
return max(b->right);
return b;
}
int deletebst(Btree *b,int e) {
Btree temp;
if(!*b) return 0;
if(e<(*b)->data)
return deletebst(&((*b)->left),e);
else
if(e>(*b)->data)
return deletebst(&((*b)->right),e);
else{
if((*b)->left && (*b)->right){
temp=min((*b)->right);
(*b)->data=temp->data;
return deletebst(&((*b)->right),temp->data);
}
else{
temp=*b;
if((*b)->left==NULL)
*b=(*b)->right;
else
if((*b)->right==NULL)
*b=(*b)->left;
free(temp);
}
}
return 1;
}
void removebst(Btree *A, Btree B){
if (!*A || !B)
return;
if ((*A)->data == B->data)
{
deletebst(A, B->data);
removebst(A, B);
removebst(A, B->right);
removebst(A, B->left);
}
else if ((*A)->data > B->data)
{
removebst(&((*A)->left), B);
removebst(A, B->right);
}
else if ((*A)->data < B->data){
removebst(&((*A)->right), B);
removebst(A, B->left);
}
}
void inorder(Btree b)
{
if (b)
{
inorder(b->left);
printf("%d ", b->data);
inorder(b->right);
}
}void preorder(Btree b)
{
if (b)
{
printf("%d ", b->data);
preorder(b->left);
preorder(b->right);
}
}
void postorder(Btree b)
{
if (b)
{
postorder(b->left);
postorder(b->right);
printf("%d ", b->data);
}
}
int main() {
int size1, size2, tests, i, num;
Bts A = NULL, B = NULL;
scanf("%d", &tests);
while (tests--)
{
A=NULL;
B=NULL;
scanf("%d", &size1);
for (i = 0; i < size1; i++){
scanf("%d", &num);
insert(&A, num);
}
scanf("%d", &size2);
for (i = 0; i < size2; i++){
scanf("%d", &num);
insert(&B, num);
}
removeB(&B, A);
Inorder(B);
printf("\n");
Preorder(B);
printf("\n");
Postorder(B);
printf("\n");
printf("\n");
}
return 0;
}