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

#define NIL NULL
struct node{
  int key;
  struct node *p;
  struct node *l;
  struct node *r;
};

typedef struct node *Node;

Node ro;

void delete1(Node k){
	Node a=k->p;
  if(k->r==NIL && k->l==NIL){
  	if(a->l==k)a->l = NIL;
  	else a->r = NIL;
	free(k);
  }else if(k->r==NIL){
  	if(a->l==k){
    	a->l = k->l;
    	k->l->p=a;
  	}else{
		a->r = k->l;
    	k->l->p=a;
	}
	k=NIL;
	free(k);
  }else if(k->l==NIL){
   	if(a->l==k){
    	a->l = k->r;
    	k->r->p=a;
  	}else{
		a->r = k->r;
    	k->r->p=a;
	}
	free(k);
  }else{
   if(k->r!=NIL){
     	a=k->r; 
	  	while(a->l!=NIL)a=a->l;
		k->key=a->key;
		delete1(a);
	  }else{
	  	a=k->p; 
	  	while(a!=NIL && k==a->r){
			k=a;
			a=a->p;
		}
		k->key=a->key;
		delete1(a);
	  }
  }
}

void delete(int k){
  Node x = ro;

  while(x != NIL && x->key!=k){
    if(k < x->key){
      x = x->l;
    }else{
      x = x->r;
    }
  }
  
  if(x== NIL){
  }else{
    delete1(x);
  }
}
Node find(int k,Node node){
  if(node == NIL){
    return node;
  }

  if(node->key == k){
    return node;
  }
  if(node->key > k){
    return find(k , node->l);
  }else{
    return find(k , node->r);
  }
}
void insert(int k){
  Node y = NIL;
  Node x = ro;
  Node z;
  
  z = malloc(sizeof(struct node));
  z->key = k;
  z->l = NIL;
  z->r = NIL;

  while(x != NIL){
    y = x;
    if(z->key < x->key){
      x = x->l;
    }else{
      x = x->r;
    }
  }
  
  z->p = y;
  if(y == NIL){
    ro = z;
  }else{
  	if(z->key < y->key){
    	y->l = z;
  	}else{
    	y->r = z;
  	}
  }
}

void inorder(Node u){
  if(u == NIL)return;
  inorder(u->l);
  printf(" %d",u->key);
  inorder(u->r);
}

void preorder(Node u){
  if(u == NIL)return;
  printf(" %d",u->key);
  preorder(u->l);
  preorder(u->r);
}

int main(){
  int n,i,j,z,k;
  char s[10];
  scanf("%d",&n);
  for(i=0;i<n;i++){
    scanf("%s",s);
    if(s[0] == 'i'){
      scanf("%d",&z);
      insert(z);
    }else if(s[0]=='f'){
      scanf("%d",&k);
      if(find(k,ro)!=NIL){
		printf("yes\n");
      }else{
		printf("no\n");
      }
    }else if(s[0]=='d'){
      scanf("%d",&k);
      delete(k);
    }else if(s[0]=='p'){
      inorder(ro);
  	  printf("\n");
      preorder(ro);
      printf("\n");
    }
  }
  free(ro);
  return 0;
}
