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

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

node *root,*NIL;


node *getMinimum(node *x);
node *find(node *u,int k);
node *getSuccessor(node *x);
void delete(node *z);
void insert(int k);
void inorder(node *p);
void preorder(node *p);



int main(void)
{
  int x;
  int i,n;
  char com[100];

  scanf("%d",&n);

  for(i = 0;i < n;i++){
      scanf("%s",com);

      if(com[0] == 'f'){
	  scanf("%d",&x);
	  
	  node *t = find(root,x);

	  if(t != NIL){
	      puts("yes");
	    } else {
	      puts("no");
	    }
	  
	} else if(strcmp(com,"insert") == 0){
	  scanf("%d",&x);
	  insert(x);
	  
	} else if(strcmp(com,"print") == 0){
	  inorder(root);
	  puts("");
	  
	  preorder(root);
	  puts("");
	  
	} else if(strcmp(com,"delete") == 0){
	  scanf("%d",&x);
	  delete(find(root,x));
	}
    }

  return 0;
}




node *getMinimum(node *x){
  while(x->left != NIL){
    x = x->left;
  }
  
  return x;
}

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

node *getSuccessor(node *x){
  if(x->right != NIL){
    return getMinimum(x->right);
  }
  
  node *y = x->parent;
  
  while(y != NIL && x == y->right){
    x = y;
    y = y->parent;
  }
  
  return y;
}

void delete(node *z)
{
  node *x,*y;

  if(z->left == NIL || z->right == NIL){
      y = z;
    } else {
      y = getSuccessor(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);
}



void insert(int k){
  node *x = root;
  node *y = NIL;
  node *z;

  z = (node *)malloc(sizeof(node));
  
  z->left = NIL;
  z->right = NIL;
  z->key = k;

  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;
  }
  if (y != NIL){
    if(y->key  >  z->key){
      y->left = z;
    } else {
      y->right = z;
    }
  }
  
}


void inorder(node *p){
  if(p != NIL){
    inorder(p->left);
    printf(" %d",p->key);
    inorder(p->right);
  } else {
    return;
  }
}


void preorder(node *p){
  if(p != NIL){
    printf(" %d",p->key);
    preorder(p->left);
    preorder(p->right);
  } else {
    return;
  }
}




