#include<cstdio>
using namespace std;
typedef struct node;
typedef node * tree;
struct node
{
	int data;
	tree lchild,rchild;
};
void insert(tree &bt,int n)
{
	if(bt)
	{
		if(bt->data>n)insert(bt->lchild,n);
		else
		if(bt->data<n)insert(bt->rchild,n);
	}
	else
	{
		bt=new node;
		bt->data=n;
		bt->lchild=bt->rchild=NULL;
		//bt->fa=NULL;
	}
}
tree find(tree bt,int n)
{
	if(bt)
	{
		if(bt->data>n)find(bt->lchild,n);
		else
		if(bt->data<n)find(bt->rchild,n);
		else
		{
			return bt;
		}
	}
	else
	return NULL;
}
void d(int turn,tree fa,tree &bt)
{
	if(turn==1)
	{
		fa->lchild=bt->rchild;
		
		d(2,fa->lchild,bt->rchild);
		delete bt->rchild; 
	}
	else
	{
		fa->rchild=bt->rchild;
		d(1,fa->rchild,bt->rchild);
		delete bt->rchild;
	}
}
tree findmin(tree node)
{
	if(node)
	{
		while(node&&node->lchild)
		{
			node=node->lchild;
		}
		return node;
	}
	return NULL;
} 
tree dele(tree node,int key)
{
	if(!node)return NULL;
	if(key<node->data)
	{
		node->lchild=dele(node->lchild,key);
		return node;
	}
	else
	if(key>node->data)
	{
		node->rchild=dele(node->rchild,key);
		return node;
	}
	else
	{
		if((!node->lchild)&&(!node->rchild))
		{
			node=NULL;
			return node; 
		}
		else
		if(!node->lchild)
		{
			node=node->rchild;
			return node;
		}
		else
		if(!node->rchild)
		{
			node=node->lchild;
			return node;
		} 
		
		tree tmp=findmin(node->rchild);
		node->data=tmp->data;
		node->rchild=dele(node->rchild,tmp->data);
		return node;
	}
}
void mid(tree bt)
{
	if(!bt)return ;
	mid(bt->lchild);
	printf(" %d",bt->data);
	mid(bt->rchild);
}
void first(tree bt)
{
	if(!bt)return ;
	printf(" %d",bt->data); 
	first(bt->lchild);
	first(bt->rchild); 
}
int main()
{
	int n;
	scanf("%d",&n);
	char s[10];
	int num;
	tree root=NULL;
	for(int i=1;i<=n;i++)
	{
		scanf("%s",s);
		if(s[0]=='i')
		{
			scanf("%d",&num);
			insert(root,num);
		}
		else
		if(s[0]=='f')
		{
			scanf("%d",&num);
			tree tmp=find(root,num);
			if(!tmp)
			printf("no\n");
			else
			printf("yes\n");
			
		}
		else
		if(s[0]=='d')
		{
			scanf("%d",&num);
			dele(root,num);
		}
		else
		{
			mid(root);
			printf("\n");
			first(root);
			printf("\n"); 
		}
	}
	return 0;
}