#include<stdio.h>
#include<stdlib.h>
#define MAX 500001
 
typedef struct cell{
 int id;
 struct cell *right;
 struct cell *left;
}cell;
 
 
void preorder(cell *root){
cell *p=root;
printf(" %d",p->id);
 
if(p->left!=NULL){preorder(p->left);}
if(p->right!=NULL){preorder(p->right);}
 
return;
}
 
void inorder(cell *root){
cell *p=root;
if(p->left!=NULL){inorder(p->left);}
printf(" %d",p->id);
if(p->right!=NULL){inorder(p->right);}
 
return;
}
 
 
cell* makecell(int x){
cell *new=malloc(sizeof(cell));
new->id=x;
new->left=NULL;
new->right=NULL;
 
return new;
}
 
void insert(cell **p,cell *new){
 
cell *temp;
 
if((*p)==NULL){(*p)=new;return;}
else{
 
 if( (*p)->left==NULL && (*p)->right==NULL ){/*子なし*/
   if((*p)->id < new->id){
     (*p)->right=new;return;}
   else{
     (*p)->left=new;return;}
  }
  else if((*p)->left==NULL&&(*p)->right!=NULL){/*左なし右あり*/
   if( (*p)->id > new->id ){
     (*p)->left=new;return;}
   else{insert(&((*p)->right),new);}
  }
  else if((*p)->left!=NULL&&(*p)->right==NULL){/*左あり右なし*/
   if( (*p)->id < new->id){
     (*p)->right=new;return;}
   else{insert(&((*p)->left),new);}
  }
  else{/*どっちも子あり*/
   if((*p)->id < new->id){
     insert(&((*p)->right),new);
   }
   else{insert(&((*p)->left),new);}
 }
}
 
return;
}
      
 
 
int find(cell *root,int x){
cell *p=root;
 
while(p!=NULL){
 if(p->id==x){return 1;}
 else if(p->id <x){p=p->right;}
 else{p=p->left;}
}
 
return 2;
}
 
 


cell* off(cell *q){
cell *temp;
cell **r;
  if(q->right==NULL&&q->left==NULL){/*子なし*/
   free(q);
   return NULL;}

  else if(q->right!=NULL&&q->left==NULL){/*右に子あり*/
     temp=q->right;
     free(q);
     return temp;}

  else if(q->right==NULL&&q->left!=NULL){/*左に子あり*/
     temp=q->left;
     free(q);
     return temp;}

  else{/*両方あり*/
    r=&(q->right);
    temp=*r;
    while(temp->left!=NULL){
     r=&(temp->left); temp=*r;
    }
    q->id=temp->id;
    *r=off(temp);
  }
return q;

}


void delete(cell **p,int x){
cell **r=p;
cell *q=*r;

while(q!=NULL){
 if(q->id==x){
  *r=off(q);
  return;
 }
 else if(q->id <x){r=&(q->right);}
 else{r=&(q->left);}
 q=*r;
}

return;
}








 
 
 
 
 
int main(){
int n,i,x,j,k;
char com[7];
cell *root=NULL;
cell *new;
int F[MAX]={0};
 
scanf("%d",&n);
 
 
for(i=0;i<n;i++){
 scanf("%s",com);
 
 switch(com[0]){
  case 'i':scanf("%d",&x);
           new=makecell(x);
           insert(&root,new);
           break;
 
  case 'p':inorder(root);
           printf("\n");
           preorder(root);
           printf("\n");
           break;
 
  case 'f':scanf("%d",&x);
           F[i]=find(root,x);
           if(F[i]==1){printf("yes\n");}
           else if(F[i]==2){printf("no\n");}
           break;

  case 'd':scanf("%d",&x);
           delete(&root,x);
           break;


 }/*switch end*/
 
}/*for end*/
 
 
 
 
return 0;
}

