// editor1
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
    int data;
    struct node *left;
    struct node *right;
}nd;
nd *root=NULL;
nd *create(int num){
    nd *newnode=(nd*)malloc(sizeof(nd));
    newnode->data=num;
    newnode->right=NULL;
    newnode->left=NULL;
    return newnode;
}
nd *insert(nd *root,int num){
    if(root==NULL)
     return create(num);
    if(num<root->data)
      root->left=insert(root->left,num);
     else
       root->right=insert(root->right,num);
    return root;
}
nd *findMn(nd *root){
    while(root->left!=NULL)
     root=root->left;
    return root;
}
nd *delete(nd *root,int *key,int *found){
    if(root==NULL)
      return NULL;
    if(key<root->data){
      root->left=delete(root->left,key,found);
    }
    else if(key>root->data){
     root->right=delete(root->right,key,found);
}
else{
    *found=1;
    if(root->left==NULL){
        nd *temp=root->right;
        free(root);
     return temp;
    }
    else if(root->right==NULL){
        nd *temp=root->left;
        free(root);
     return temp;
    }

nd *temp=findMn(root->right);
root->data=temp->data;
root->left=delete(root->right,key,found);
}
return root;
}
int main(){
    int n,num;
    int key,found=0;
    nd *root=NULL;
    if(n<0){
        printf("Invalid input");
        return 0;
    }
    for(int i=0;i<n;i++){
        scanf("%d",&num);
        root=insert(root,num);
    }
    scanf("%d",&key);
    delete(root,key,found);
    return 0;
}