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

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

nodeinfo root = NULL;

void insert(int key){
  nodeinfo x = root;
  nodeinfo y = NULL;
  nodeinfo t;
  t = (nodeinfo)malloc(sizeof(*t));
  t->key = key;
  t->left = NULL;
  t->right = NULL;
  while(x != NULL){
    y = x;
    if(t->key < x->key) x = x->left;
    else x = x->right;
  }
  t->parent = y;
  if(y == NULL) root = t;
  else if(t->key < y->key) y->left = t;
  else y->right = t;
}

int find(nodeinfo x, int key){
  if(key == x->key) return 1;
  else if(key < x->key){
    if(x->left == NULL) return 0;
    else return find(x->left, key);
  }
  else{
    if(x->right == NULL) return 0;
    else return find(x->right, key);
  }
  return 0;
}

nodeinfo getNext(nodeinfo x){
  if(x->left != NULL) return getNext(x->left);
  if(x->right != NULL) return getNext(x->right);
  if(x->left == NULL && x->right == NULL) return x;
}

void remove(nodeinfo x, int key){
  if(key == x->key){
    nodeinfo child;
    if(x->left == NULL && x->right == NULL) child = NULL;
    else if(x->left != NULL && x->right != NULL){
      nodeinfo dst = getNext(x->right);
      x->key = dst->key;
      remove(dst, dst->key);
      return;
    }
    else{
      if(x->left != NULL) child = x->left;
      else child = x->right;
    }
    nodeinfo parent = x->parent;
    if(parent->left != NULL && parent->left->key == key) parent->left = child;
    if(parent->right != NULL && parent->right->key == key) parent->right = child;
    if(!(x->left == NULL && x->right == NULL)) child->parent = parent;
    free(x);
  }
  else if(key < x->key) remove(x->left, key);
  else remove(x->right, key);
}

void inorder(nodeinfo x){
  if(x->left != NULL) inorder(x->left);
  printf(" %d", x->key);
  if(x->right != NULL) inorder(x->right);
}

void preorder(nodeinfo x){
  printf(" %d", x->key);
  if(x->left != NULL) preorder(x->left);
  if(x->right != NULL) preorder(x->right);
}

int main() {
  int i, n, key;
  char command[7];
  scanf("%d", &n);
  for(i = 0; i < n; i++){
    scanf("%s", command);
    if(command[0] == 'p'){
      inorder(root);
      printf("\n");
      preorder(root);
      printf("\n");
      continue;
    }
    scanf("%d", &key);
    if(command[0] == 'i') insert(key);
    else if(command[0] == 'f'){
      if(find(root, key) == 1) printf("yes\n");
      else printf("no\n");
    }
    else remove(root, key);
  }
  return 0;
}
