class Node
	attr_accessor :key, :right, :left, :parent
	def initialize(key, right, left, parent)
		@key = key; @right = right; @left = left; @parent = parent
	end
end

$none = Node.new(0, nil, nil, nil)
$root = $none

def treeMinimum(x)
	while x.left != $none
		x = x.left
	end
	return x
end

def find(u, k)
	while u != $none && k != u.key
		if k < u.key
			u = u.left
		else
			u = u.right
		end
	end
	return u
end

def treeSuccessor(x)
	return treeMinimum(x.right) if x.right != $none
	y = x.parent
	while y != $none && x == y.right
		x = y
		y = y.parent
	end
	return y
end

def treeDelete(z)
	if z.left == $none || z.right == $none
		y = z
	else
		y = treeSuccessor(z)
	end

	if y.left != $none
		x = y.left
	else
		x = y.right
	end

	x.parent = y.parent if x != $none

	if y.parent == $none
		$root = x
	else
		if y == y.parent.left
			y.parent.left = x
		else
			y.parent.right = x
		end
	end

	z.key = y.key if y != z
end

def insert(k)
	y = $none	
	x = $root
	z = Node.new(k, $none, $none, $none)

	#cnt = 0
	while x != $none
		#puts cnt
		#cnt += 1

		y = x
		if z.key < x.key
			x = x.left
		else
			x = x.right
		end
	end

	z.parent = y
	if y == $none
		$root = z
	else
		if z.key < y.key
			y.left = z
		else
			y.right = z
		end
	end
end

def inorder(u)
	return if u == $none
	inorder(u.left)
	printf(" %d", u.key)
	inorder(u.right)
end

def preorder(u)
	return if u == $none
	printf(" %d", u.key)
	preorder(u.left)
	preorder(u.right)
end

n = gets.to_i
0...n.times do |i|
	line = gets.split
	com = line[0]
	if com == "insert"
		insert(line[1].to_i)
	elsif com == "print"
		inorder($root)
		puts
		preorder($root)
		puts
	elsif com == "find"
		t = find($root, line[1].to_i)
		if t != $none
			puts "yes"
		else
			puts "no"
		end
	elsif com == "delete"
		treeDelete(find($root, line[1].to_i))
	end
end