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

typedef struct P{
    int key,pri;
    struct P *left,*right,*parent;
}Node;

Node *root,*NIL;

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

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

void insert(int key){
    Node *y,*x,*z;
    y=NIL; x=root;
    z=(Node*)malloc(sizeof(Node));
    z->key=key; z->left = NIL; z->right=NIL;
    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;
        }
    }
}

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

Node* treeMin(Node *x){
    while(x->left!=NIL){
        x=x->left;
    }
    return x;
}

Node* treeSuccessor(Node *x){
    Node *y;
    if(x->right!=NIL){return treeMin(x->right);}
    /*y=x->parent;
    while(y!=NIL&&x==y->parent){
        x=y;
        y=y->parent;
    }*/
    return y;
}

void delete(int key){
    Node *x,*y,*z;
    z = find(root,key);
    if(z->left==NIL||z->right==NIL){y=z;}
    else{
        y = treeSuccessor(z);
    }
    if(y->left!=NIL){
        x=y->left;
    }else{
        x=y->right;
    }
    if(x!=NIL){
        x->parent=y->parent;
    }
    if(y->parent==NIL){
        root=x;
    }else if(y==y->parent->left){
        y->parent->left=x;
    }else{
        y->parent->right=x;
    }
    if(y!=z){
        z->key=y->key;
    }
    free(y);
}

int main(void){
    int n,i,j,x,y;
    char str[7];
    Node *node;
    scanf("%d",&n);
    for(i=0;i<n;i++){
        scanf("%s",str);
        if(str[0]=='i'){
            scanf("%d",&y);
            insert(y);
            x++;
        }else if(str[0]=='f'){
            scanf("%d",&y);
            node = find(root,y);
            if(node!=NIL){printf("yes\n");}
            else{printf("no\n");}
        }else if(str[0]=='d'){
            scanf("%d",&y);
            delete(y);
        }else{
            ino(root);
            printf("\n");
            pre(root);
            printf("\n");
        }
    }
    return 0;
}

