#include <stdio.h>
#include <stdlib.h>
#define NIL NULL  
struct node{
  struct node *r;
  struct node *l;
  struct node *p;
  int key;
};

typedef struct node * Node;
Node root;
Node find(Node u, int k);
void insert(int k);
void inorderTreeWalk(Node x);
void preorderTreeWalk(Node x);
Node treeMinimum(Node x);
Node treeSearch(Node x,int k);
Node treeSuccessor(Node x);
void treeDelete(Node z);
int main()
{
  char str[7];
  int m,i,x,key;
  scanf("%d",&m);
  for( i=0 ; i<m ; i++ ){
    scanf("%s",str);
    if(str[0]=='i'){
      scanf("%d",&x);
      insert(x);
    }
    else if(str[0]=='p'){
      inorderTreeWalk(root);
      printf("\n");
      preorderTreeWalk(root);
      printf("\n");
    }
    else if(str[0]=='d'){
      scanf("%d",&key);
      if( find(root,key)==NIL ){
	printf("no\n");
      }else{
	printf("yes\n");
      }   
    }
    else{
      scanf("%d",&x);
      treeDelete(treeSearch(root,x));
    }
  }
  return 0;
   
}

Node find(Node u, int k){
      if( u == NIL || k == u->key ){
          return u;
      }  
      if( k < u->key ){
        return find(u->l,k);
      }else{
        return find(u->r,k);
      }
}

void insert(int k)
{
  Node x;
  Node y;
  Node z;
  y = NIL;
  x = root;
  z = (Node)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 inorderTreeWalk(Node x)
{
  if(x==NIL) return;
  inorderTreeWalk(x->l);
  printf(" %d",x->key);
  inorderTreeWalk(x->r);
}
 
void preorderTreeWalk(Node x)
{
  if(x==NIL) return;
    printf(" %d",x->key);
    preorderTreeWalk(x->l);
    preorderTreeWalk(x->r);
   
}
Node treeMinimum(Node x)
{
  while(x->l!=NIL) x = x->l;
  return x;
}
 
Node treeSearch(Node x,int k){
  if(x==NIL || k==x->key) return x;
  if(k<x->key) return treeSearch(x->l,k);
  
  else return treeSearch(x->r,k);
}
 
 
Node treeSuccessor(Node x)
{
  Node y;
  if(x->r!=NIL) return treeMinimum(x->r);
 
  y = x->parent;
  while(y!=NIL && x==y->r){
    x = y;
    y = y->p;
  }
  return y;
}
 
 
void treeDelete(Node z)
{
  Node x, y;
  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;
}