#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct node{
    int key;
    struct node *parent,*left,*right;
}node;
#define N 500000

int m;
node *NIL,*root;

void insert(node *z){
    node *y=NIL;
    node *x=root;
    while(x!=NIL){
        y=x;
        if(z->key<x->key)x=x->left;
        else x=x->right;
        z->parent=y;
    }
    if(y==NIL)root=z;
    else if(z->key<y->key)y->left=z;
    else y->right=z;

}

void inparse(node *u){
  if(u==NIL)return;
  inparse(u->left);
  printf(" %d",u->key);
  inparse(u->right);
}

void preparse(node *u){
  if(u==NIL)return;
  printf(" %d",u->key);
  preparse(u->left);
  preparse(u->right);
}

node* find(int k){
    node *x=root;
    while(x!=NIL&&k!=x->key){
        if(k<x->key)x=x->left;
        else x=x->right;
    }
    return x;
}

node* get(node* z){
    node *y;
    if(z->right!=NIL){
        z=z->right;
        while(z->left!=NIL)z=z->left;
        return z;
    }
    y=z->parent;
    while(y!=NIL&&z==y->right){
        z=y;
        y=y->parent;
    }
    return y;
}

void delete(int k){
    node *z,*y,*x;
    z=find(k);
    if(z->left==NIL||z->right==NIL) y=z;
    else y=get(z);

    if(y->left!=NIL)x=y->left;
    else x=y->right;
    if(x!=NIL)x->parent=y->parent;
    if(y==NIL)x=root;
    else if(y->parent->left==y)y->parent->left=x;
    else y->parent->right=x;
    if(y!=z)z->key=y->key;

}

int main(){
    int i,n;
    char str[6];
    node *z,*a;

    scanf("%d",&m);
    for(i=0;i<m;i++){
        scanf("%s",str);
        if(strcmp(str,"insert")==0){
        
            scanf("%d",&n);
            
            z=(node*)malloc(sizeof(node));
            z->key=n;
            
            z->left=NIL;
            z->right=NIL;
            insert(z);
        }
        else if(strcmp(str,"print")==0){
            inparse(root); 
            printf("\n"); 
            preparse(root);
            printf("\n");  
        }
        else if(strcmp(str,"find")==0){
            scanf("%d",&n);
            a=find(n);
            if(a==NIL)printf("no\n");
            else printf("yes\n");
        }
        else if(strcmp(str,"delete")==0){
            scanf("%d",&n);
            delete(n);
        }
    }
    return 0;
}

