#include<iostream>
using namespace std;

struct Node {
	int key;
	Node *p, *l, *r;
};

Node *nil;
Node *root = nil;

void insert(int k) {
	Node *y = nil;
	Node *x = root;
	Node *z = new Node;
	z->key = k;
	z->l = nil;
	z->r = nil;
	while (x != nil) {
		y = x;
		if (z->key < 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(Node *root) {
	if (root == nil) return;
	inorder(root->l);
	cout << ' ' << root->key;
	inorder(root->r);
}

void preorder(Node *root) {
	if (root == nil) return;
	cout << ' ' << root->key;
	preorder(root->l);
	preorder(root->r);
}

void print() {
	inorder(root);
	cout << endl;
	preorder(root);
	cout << endl;
}

Node * findNode(int key) {
	Node *x = root;
	while (x != nil && key != x->key) {
		if (key < x->key) x = x->l;
		else x = x->r;
	}
	return x;
}

void find(int key) {
	if (findNode(key) == nil) cout << "no" << endl;
	else cout << "yes" << endl;
}

Node * getMinimum(Node *x) {
	while (x->l != nil) {
	x = x->l;
	}
	return x;
}

Node * getSuccessor(Node *x) {
	return getMinimum(x->r);
}

void del(Node *x) {
	if (x->l == nil && x->r == nil) {
		if (x == root) delete(x);
		if(x->p->l == x) {
			x->p->l = nil;
			delete(x);
		} else {
			x->p->r = nil;
			delete(x);
		}
	} else if (x->l == nil) {
		if (x == root) {
			x->r->p = nil;
			root = x->r;
			delete(x);
		}
		if (x->p->l == x) {
			x->p->l = x->r;
			x->r->p = x->p;
			delete(x);
		} else {
			x->p->r = x->r;
			x->r->p = x->p;
			delete(x);
		}
	} else if (x->r == nil) {
		if (x == root) {
			x->l->p = nil;
			root = x->l;
			delete(x);
		}
		if (x->p->l == x) {
			x->p->l = x->l;
			x->l->p = x->p;
			delete(x);
		} else {
			x->p->r = x->l;
			x->l->p = x->p;
			delete(x);
		}
	} else {
		x->key = getSuccessor(x)->key;
		del(getSuccessor(x));
	}
}

void deleteNode(int key) {
	Node *x = findNode(key);
	if (x == nil) return;
	del(x);
}

int main() {
	int n, key;
	char cmd[10];
	cin >> n;
	for (int i = 0; i < n; i++) {
		cin >> cmd;
		if (cmd[0] == 'i') {
			cin >> key;
			insert(key);
		} else if (cmd[0] == 'f') {
			cin >> key;
			find(key);
		} else if (cmd[0] == 'd') {
			cin >> key;
			deleteNode(key);
		} else print();
	}

	return 0;
}