#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct node{
  int key;
  struct node *p;
  struct node *r;
  struct node *l;
} Tree;
Tree *root = NULL;

void insert(int key){
  Tree *z = (Tree*)malloc(sizeof(Tree));
  z -> key = key;
  z -> l = NULL;
  z -> r = NULL;
  Tree *x, *y;
  x = root;
  y = NULL;
  while(x != NULL){
    y = x;
    if(z -> key < x -> key)
      x = x -> l;
    else
      x = x -> r;
  }
  z -> p = y;
  if(y == NULL)
    root = z;
  else if(z -> key < y -> key) 
    y -> l = z;
  else
    y -> r = z;
}
Tree* find(int key){
  Tree *c = root;
  while(c != NULL){
    if(c -> key == key){
      printf("yes\n");
      return c;
    }else if(key < c -> key)
      c = c -> l;
    else
      c = c -> r;
  }
  printf("no\n");
  return NULL;
}
Tree* treeMinimum(Tree *x){
  while(x -> l != NULL)
    x = x -> l;
  return x;
}
Tree* treeSuccessor(Tree *x){
  if(x -> r != NULL)
    return treeMinimum(x -> r);
  Tree *y = x -> p;
  while(y != NULL && x == y -> r){
    x = y;
    y = y -> p;
  }
  return y;
}
void delete(Tree *c){
  Tree *x, *y;
  if(c -> l == NULL || c -> r == NULL)
    y = c;
  else
    y = treeSuccessor(c);
  if(y -> l != NULL)
    x = y -> l;
  else
    x = y -> r;

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

  if(y != c)
    c -> key = y -> key;
  
  free(y);
}
void printInorder(Tree *u){
  if(u == NULL)
    return;
  printInorder(u -> l);
  printf(" %d", u -> key);
  printInorder(u -> r);
}
void printPreorder(Tree *u){
  if(u == NULL)
    return;
  printf(" %d", u -> key);
  printPreorder(u -> l);
  printPreorder(u -> r);
}

int main(){
  int n, key;
  char line[100];
  char *str_ptr, *key_ptr;

  fgets(line, sizeof(line), stdin);
  sscanf(line, "%d", &n);
  for(int i = 0; i < n; ++i){
    fgets(line, sizeof(line), stdin);
    if(strcmp(line, "print") == 0 || strcmp(line, "print\n") == 0){
      printInorder(root);
      printf("\n");
      printPreorder(root);
      printf("\n");
    }else{
      str_ptr = strtok(line, " ");
      key_ptr = strtok(NULL, " ");
      sscanf(key_ptr, "%d", &key);
      if(strcmp(str_ptr, "insert") == 0)
        insert(key);
      else if(strcmp(str_ptr, "find") == 0)
        find(key);
      else if(strcmp(str_ptr, "delete") == 0){
        Tree *c = find(key);
        delete(c);
      }
    }
  }
  return 0;
}

