#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct node {
	int key;
	struct node *r,*l,*p;
};
struct node *NIL,*root;
int a=0,b=0;
void insert(int k) {
	struct node *x=root,*y=NIL,*z;
	z=(struct node*)malloc(sizeof(struct node));
	z->key=k;
	z->l=NIL;
	z->r=NIL;
	while(x!=NIL) {
		y=x;
		if(k<x->key)
			x=x->l;
		else
			x=x->r;
	}
	z->p=y;
	if(y==NIL) {
		root=z;
	} else if(z->key<y->key)
		y->l=z;
	else
		y->r=z;
}
void inOrder(struct node *p) {
	if(p==NIL)
	return;
	inOrder(p->l);
    printf(" %d",p->key);
	inOrder(p->r);
}
void preOrder(struct node *p) {
	if(p==NIL)
	return;
	printf(" %d",p->key);
	preOrder(p->l);
	preOrder(p->r);
}
int print(struct node *p) {
	a=0;
	b=0;
	inOrder(p);
	printf("\n");
	preOrder(p);
	printf("\n");
	return a;
}
struct node *find(struct node *x,int k){
	while(x!=NIL&&x->key!=k){
		if(k>x->key)
		x=x->r;
		else
		x=x->l;
	}
	return x;
}
struct node *getMin(struct node *x){
	while(x->l!=NIL){
		x=x->l;
	}
	return x;
}
struct node *getSuccessor(struct node *z){
	if(z->r!=NIL)
	return getMin(z->r);
	
	struct node *y=z->p;
	while(y!=NIL&&z==y->r){
		z=y;
		z=y->p;
	}
	return y;
}
void deleteNode(struct node *z){
	struct node *x,*y;
	if(z->l==NIL||z->r==NIL)
	y=z;
	else
	y=getSuccessor(z);
	
	if(y->l==NIL)
	x=y->r;
	else
	x=y->l;
	
	if(x!=NIL)
	x->p=y->p;
	
	if(y->p==NIL)
	root=x;
	else if(y==y->p->l)
	y->p->l=x;
	else
	y->p->r=x;
	
	if(y!=z)
	z->key=y->key;
}
int main() {
	int m,i,j,o=0,k;
	char str[10];
	int len[11];
	struct node *x;
	scanf("%d",&m);
	for(i=0; i<m; i++) {
		scanf("%s",str);
		if(str[0]=='i') {
			scanf("%d",&k);
			insert(k);
		} else if(str[0]=='p'){
			print(root);
		}
		else if(str[0]=='d'){
			scanf("%d",&k);
			deleteNode(find(root,k));
		}
		else{
			scanf("%d",&k);
			x=find(root,k);
			if(x!=NIL)
			printf("yes\n");
			else
			printf("no\n");
		}
	}//输入
	return 0;
}
