#include <stdio.h>
#define N 500000

typedef struct{
  int par;
  int left;
  int right;
  int key;
}node;

node T[N];
int root;

void Tree_insert(int,int);
void node_delete(int);
void preorder(int);
void inorder(int);

int main(){
  int n,x,i,j,k=0;
  int find[N];
  char c[10];

  scanf("%d",&n);

  for(i=0; i<n; i++) T[i].left = T[i].right = T[i].key = -1;

  for(i=0; i<n; i++){
  
  scanf("%s",&c);

    if(c[0] == 'i'){
      scanf("%d",&x);

      Tree_insert(i,x);

    }

    if(c[0] == 'f'){

      scanf("%d",&x);

      for(j=0;j<i;j++){

	if(T[j].key == x){


	  find[k] = 1;

	  break;
	}
      }

      k++;

    }

    if(c[0] == 'd'){
      scanf("%d",&x);

      node_delete(x);

    }

    if(c[0] == 'p'){

      for(j=0;j<k;j++){
	if(find[j] == 1) printf("yes\n");
	else printf("no\n");

      }

      k = 0;

      inorder(0);
      printf("\n");

      preorder(0);
      printf("\n");
   
    }
  }

  for(j=0;j<k;j++){

    if(find[j] == 1) printf("yes\n");
    else printf("no\n");

  } 

  return 0;
}

void Tree_insert(int n,int x){
  int a,i;

  if(n == 0){
    T[n].par = -1; 
    T[n].key = x;
    root = 0;

  }
  else{

    a = root;  
    while(1){
  
    if(T[a].key > x && T[a].left == -1){

	T[a].left = n;
	T[T[a].left].par = a;
	T[T[a].left].key = x;
	break;

      }

      if(T[a].key < x && T[a].right == -1){

	T[a].right = n;
	T[T[a].right].par = a;
	T[T[a].right].key = x;
	break;

      }

      if(T[a].key > x) a = T[a].left;

      else a = T[a].right;
    }			   
  }
}

void node_delete(int x){
  int n,i=0;

  while(1){
    if(T[i].key == x) break;

    i++;
  }

  if(T[i].left == -1 && T[i].right == -1){
    if(T[T[i].par].left == i) T[T[i].par].left = -1;
    else T[T[i].par].right = -1;
  }
else{

    if(T[i].left != -1){
      if(T[T[i].par].key > T[i].key){
	T[T[i].par].left = T[i].left;
	T[T[i].left].par = T[i].par;
      }else{
	T[T[i].par].right = T[i].left;
	T[T[i].left].par = T[i].par;
      }
    }
    else{
      if(T[i].right != -1){
	if(T[T[i].par].key > T[i].key){
	  T[T[i].par].left = T[i].right;
	  T[T[i].right].par = T[i].par;
	}
	else{
	  T[T[i].par].right = T[i].right;
	  T[T[i].right].par = T[i].par;

	}
      }
      else{
	n = i;
	i = T[i].right;
	
	while(1){
	  if(T[i].left == -1) break;
	  i = T[i].left;
	}
	
	if(T[T[n].par].left == n) T[T[n].par].left = i;
	
	else T[T[n].par].right = i;
      }
    }
  }
}

void preorder(int n){

  printf(" %d",T[n].key);

  if(T[n].left != -1) preorder(T[n].left);


  if(T[n].right != -1) preorder(T[n].right);

}

void inorder(int n){


  if(T[n].left != -1) inorder(T[n].left);

  printf(" %d",T[n].key);

  if(T[n].right != -1) inorder(T[n].right);
}