class Node
  attr_accessor :key, :left, :right, :parent
  def initialize key
    @key = key
  end
   
  def inorder
    left.inorder if left
    print " #{key}"
    right.inorder if right
  end
   
  def preorder
    print " #{key}"
    left.preorder if left
    right.preorder if right
  end
end
   
def insert
  z = Node.new($key.to_i)
  x = $root
  while x
    y = x
    x = z.key < x.key ? x.left : x.right
  end
   
  unless y
    $root = z
  else
    z.key < y.key ? y.left = z : y.right = z
    z.parent = y
  end
end
 
def find(x)
  y = $root
  while y
    return y if y.key == x
    z = y
    y = x < y.key ? y.left : y.right
  end
  return nil
end
 
def delete(x)
  y = find(x)
  z = position(y)
  if y.right.nil? || y.left.nil? then delete2(y,z)
  else
    p = y.right
    while p
      break if p.left == nil
      p = p.left
    end
    y.key = p.key
    z = position(p)
    delete2(p,z)
  end
end
 
def position(n)
  n.parent.right && n.parent.right.key == n.key
end
 
def delete2(y,z)
  if y.left.nil? && y.right.nil?
    z ? y.parent.right = nil : y.parent.left = nil
  elsif y.left.nil?
    if z 
      y.parent.right = y.right
      y.parent.right.parent = y.parent
    else
      y.parent.left = y.right
      y.parent.left.parent = y.parent
    end
  elsif y.right.nil?
    if z
      y.parent.right = y.left
      y.parent.right.parent = y.parent
    else
      y.parent.left = y.left
      y.parent.left.parent = y.parent
    end
  end
end
 
n = gets.to_i
n.times do
  command, $key = gets.split
  case command
  when "insert"
    insert
  when "find"
    if find($key.to_i)
      puts "yes"
    else
      puts "no"
    end
  when "delete"
    delete($key.to_i)
  else
    $root.inorder
    puts ""
    $root.preorder
    puts ""
  end
end