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

	attr_accessor :root

	def insert(key)
		parent  = nil
		current = @root
		while current
			parent = current
			if key < current.key
				current = current.left
			else
				current = current.right
			end
		end

		new_node = Node.new(key, parent)
		if !parent
			@root = new_node
		elsif key < parent.key
			parent.left = new_node
		else
			parent.right = new_node
		end
		self
	end

	def find(key)
		current = @root
		while current && current.key != key
			if key < current.key
				current = current.left
			else
				current = current.right
			end
		end
		current
	end

	def delete(key)
		target = find(key)
		return nil unless target
		delete_helper(target)
	end

	def keys_inorder
		inorder_helper(@root)
	end

	def keys_preorder
		preorder_helper(@root)
	end

	private
	def copy_node(node, new_key=nil)
		new_key ||= node.key

		copied = Node.new(new_key, node.parent)
		copied.left  = node.left
		copied.right = node.right
		copied
	end

	def replace(node, new_node)
		parent = node.parent
		new_node.parent = parent if new_node

		if !parent
			@root = new_node
		elsif parent.left && parent.left.key == node.key
			parent.left = new_node
		else
			parent.right = new_node
		end

		node
	end

	def delete_helper(node)
		if node.left && node.right
			copied = copy_node(node, node.right.key)
			replace(node, copied)

			delete_helper(node.right)
			return node # 元々の削除対象を返したい為
		end

		return replace(node, node.left)  if node.left
		return replace(node, node.right) if node.right
		replace(node, nil)
	end

	def inorder_helper(node)
		return [] unless node
		result = []
		result.concat(inorder_helper(node.left))
		result << node.key
		result.concat(inorder_helper(node.right))
	end

	def preorder_helper(node)
		return [] unless node
		result = [node.key]
		result.concat(preorder_helper(node.left))
		result.concat(preorder_helper(node.right))
	end

end

tree = BinarySearchTree.new
n = STDIN.gets.to_i
n.times do
	command, param = STDIN.gets.split[0..1]
	if command == "insert"
		tree.insert(param.to_i)

	elsif command == "find"
		puts (tree.find(param.to_i) ? "yes" : "no")

	elsif command == "delete"
		tree.delete(param.to_i)

	elsif command == "print"
		puts " #{tree.keys_inorder.join(" ")}"
		puts " #{tree.keys_preorder.join(" ")}"

	else
		raise "Unexpected input #{command}, #{param}"
	end
end