#include<stdio.h>
#include<stdlib.h>
#include<string.h>

struct Node{
  int key;
 struct Node *r,*l,*p;
};

struct Node *root,*NIL;

void insert(int);
void inorder(struct Node *);
void preorder(struct Node *);
struct Node * find(struct Node *,int);
struct Node * treeMinmum(struct Node *);
struct Node * treeSuccessor(struct Node *);
void treeDelete(struct Node *);

int main(){
  int n,i,x;
  char com[100];

  scanf("%d",&n);
  for(i=0;i<n;i++){
    scanf("%s",com);
    if(com[0]=='f'){
      scanf("%d",&x);
      struct Node *t=find(root,x);
      if(t!=NIL) printf("yes\n");
      else printf("no\n");
    }
    else if(com[0] =='i'){
      scanf("%d",&x);
      insert(x);
    }
    else if(com[0]=='p'){
      inorder(root);
      printf("\n");
      preorder(root);
      printf("\n");
    }
    else if(com[0]=='d'){
      scanf("%d",&x);
      treeDelete(find(root,x));
    }
  }
  
  return 0;
}

void insert(int k){
  struct Node *y=NIL;
  struct Node *x=root;
  struct Node *z; 

  z=malloc(sizeof(struct Node));
  z->key=k;
  z->l=NIL;
  z->r=NIL;

  while(x!=NIL){
    y=x;
    if( z->key < x->key){
      x=x->l;
    }
    else{
 x=x->r;
    }
  }

  z->p=y;
  if(y==NIL){
    root=z;
  }
  else{
    if( z->key<y->key){
      y->l=z;
    }
    else{
      y->r=z;
    }
  }
}

void inorder(struct Node *u){
  if(u==NIL) return;
  inorder(u->l);
  printf(" %d",u->key);
  inorder(u->r);
}

void preorder(struct Node *u){
 if(u==NIL) return;
 printf(" %d",u->key);
 preorder(u->l);
 preorder(u->r);
}

struct Node * find(struct Node *u,int k){
  while(u!=NIL && k!=u->key){
    if(k < u->key) u=u->l;
    else u=u->r;
  }
  return u;
}

struct Node * treeMinmum(struct Node *x){
  while(x->l!=NIL) x=x->l;
  return x;
}

struct Node * treeSuccessor(struct Node *x){
  if(x->r!=NIL) return treeMinmum(x->r);
  struct Node *y;
  y=x->p;
  while(y!=NIL && x==y->r){
    x=y;
    y=y->p;
  }
  return y;
}

void treeDelete(struct Node *z){
  struct Node *y,*x;
  if(z->l==NIL || z->r==NIL) y=z;
  else y =treeSuccessor(z);

  if(y->l!=NIL){
    x=y->l;
  }
  else {
    x=y->r;
  }

 if(x!=NIL){
   x->p=y->p;
 }

if(y->p==NIL){
  root=x;
 }
 else {
   if(y==y->p->l){
     y->p->l=x;
   }
   else {
     y->p->r=x;
   }
 }

if(y!=z){
  z->key=y->key;
 }

 free(y);
}

