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

struct node{
  struct node *parent;
  struct node *right;
  struct node *left;
  int key;
};

typedef struct node *Tree;

#define NILL NULL

Tree tree;


void TreeInsert(int k){
  Tree m = NILL;
  Tree l = tree;
  Tree n;

  n = malloc(sizeof(struct node));
  n->key = k;
  n->left = NILL;
  n->right = NILL;

  while(l != NILL){
    m = l;
    if(n->key < l->key){
      l = l->left;
    }
    else{
      l = l->right;
    }
  }
  n->parent = m;
  
  if(m == NILL){
    tree = n;
  }
  else if(n->key < m->key){
    m->left = n;
  }
  else{
    m->right = n;
  }
}

void TreePreorder(Tree n){
  if(n != NILL){
    printf(" %d",n->key); 
    TreePreorder(n->left);
    TreePreorder(n->right);
  }
}

void TreeInorder(Tree n){
  if(n != NILL){
    TreeInorder(n->left);
    printf(" %d",n->key);
    TreeInorder(n->right);
  }
}
Tree TreeMin(Tree n){
  while(n->left != NILL){
    n = n->left;
  }
  return n;
}

Tree TreeSearch(Tree n,int k){
  if(n == NILL || k == n->key){
    return n;
  }
  if(k < n->key){
    return TreeSearch(n->left,k);
  }
  else{
    return TreeSearch(n->right,k);
  }
}

Tree TreeCreate(Tree n){
  Tree m;

  if(n->right != NILL){
    return TreeMin(n->right);
  }
  m = n->parent;
  while(m != NILL && n == m->right){
    n = m;
    m = m->parent;
  }
  return m;
}

void TreeDelete(Tree n){
  Tree m;
  Tree l;

  if(n->left == NILL || n->right == NILL){
    m = n;
  }
  else{
    m = TreeCreate(n);
  }

  if(m->left != NILL){
    l = m->left;
  }
  else{
    l = m->right;
  }

  if(l != NILL){
    l->parent = m->parent;
  }

  if(m->parent == NILL){
    tree = l;
  }
  else if(m == m->parent->left){
    m->parent->left = l;
  }
  else{
    m->parent->right = l;
  }

  if(m != n){
    n->key = m->key;
  }
}

int main(){
  int n,i,j;
  char command[10];
  scanf("%d",&n);

  for(i - 0;i < n;i++){
    scanf("%s",command);
    if(command[0] == 'i'){
      scanf("%d",&j);
      TreeInsert(j);
    }
    else if(command[0] == 'p'){
      TreeInorder(tree);
      printf("\n");
      TreePreorder(tree);
      printf("\n");
    }
    else if(command[0] == 'f'){
      scanf("%d", &j);
      Tree temp = TreeSearch(tree,j);
      if(temp != NILL)printf("yes\n");
      else printf("no\n");
    }
    else if(command[0] == 'd'){
      scanf("%d",&j);
      TreeDelete(TreeSearch(tree,j));
    }
  }
  return 0;
}