#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define NIL -1
struct node{
  int key;
  struct node* right;
  struct node* left;
  struct node* parent;
};
typedef struct node* nodepointer;
nodepointer none;
nodepointer root;

nodepointer treeMinimum(nodepointer x){
  while(x->left != none)x = x->left;
  return x;
}
nodepointer treeSuccessor(nodepointer x){
  nodepointer y;
  if(x->right != none)return treeMinimum(x->right);
  y = x->parent;
  while(y != none && x == y->right){
    x = y;
    y = y->parent;
  }
  return y;
}

/*
void insert(int data){
  nodepointer y = NULL;
  nodepointer x = root;
  nodepointer new;
  new = malloc(sizeof(struct node));
  new->key = data;
  new->left = NULL;
  new->right = NULL;
  while(new != NULL){
    y = x;
    if(new->key < x->key){
      x = x->left;
    }else{
      x = x->right;
    }
  }
  new->parent = y;
  if(y == NULL){
    root = new;
  }else{
    if(new->key < y->key){
      y->left = new;
    }else{
      y->right = new;
    }
  }
}
*/
void insert(int k){
struct node *y = NULL;
struct node *x = root;
struct node *z;
 
z = malloc(sizeof(struct node));
z->key = k;
z->left = NULL;
z->right = NULL;

while(x != NULL){
y = x;
 if(z->key < x->key){
x = x->left;
}else{
x = x->right;
}
}

z->parent = y;

if(y == NULL){
root = z;
}else{
if(z->key < y->key){
y->left =  z;
}else{
y->right = z;
}
}
}




nodepointer find(nodepointer u,int data){
  while(u != NULL && data != u->key){
    if(data < u->key)u = u->left;
    else u = u->right;
  }
  return u;
}
void inorder(nodepointer u){
  if(u == NULL)return;
  inorder(u->left);
  printf(" %d",u->key);
  inorder(u->right);
}

void preorder(nodepointer u){
  if(u == NULL)return;
  printf(" %d",u->key);
  preorder(u->left);
  preorder(u->right);

}
void delete(nodepointer z){
  nodepointer y;
  nodepointer x;
  if(z->left == none || z->right == none)y = z;
  else y = treeSuccessor(z);
  if(y->left != none){
    x = y->left;
  }else{
    x = y->right;
  }
  if(x != none){
    x->parent = y->parent;
  }
  if(y->parent == none){
    root = x;
  }else{
    if(y == y->parent->left){
      y->parent->left = x;
    }else{
      y->parent->right = x;
    }
  }
  if(y != x){
    z->key = y->key;
  }
  free(y);
}

int main(){
  int datanum,temp,i;
  char command[11];
  nodepointer a;
  scanf("%d",&datanum);
  for(i=0;i<datanum;i++){
    scanf(" %s",command);
    if(command[0] == 'i'){
      scanf(" %d",&temp);
      insert(temp);
    }else if(command[0] == 'f'){
      scanf(" %d",&temp);
      a = find(root,temp);
      if(a != none)printf("yes\n");
      else printf("no\n");
    }else if(command[0] == 'p'){
      inorder(root);
      printf("\n");
      preorder(root);
      printf("\n");
    }else if(command[0] == 'd'){
      scanf(" %d",&temp);
      delete(find(root,temp));
    }
  }
  return 0;
}

