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
  def in
    left.in if left
    $a << self
  end
end

def insert
  z = Node.new $key
  x = $root
  while x
    y = x
    x = z.key < x.key ? x.left : x.right
  end
  z.parent=y
  unless y
    $root = z
  else
    z.key < y.key ? y.left = z : y.right = z
  end
end

def find root
  if root == nil
    puts 'no'
  elsif $key == root.key
    puts 'yes'
  elsif $key < root.key
    find root.left
  else
    find root.right
  end
end

def delete root
  left = root.left
  right = root.right
  if $key == root.key
    parent = root.parent
    pleft = parent.left if parent
    if (left || right) == nil
      if parent.left
        $key == pleft.key ? parent.left = nil : parent.right = nil
      else
        parent.right = nil
      end
    elsif left && right
      $a=[]
      right.in
      root.key = $key = $a[0].key
      delete $a[0]
    elsif left
      if parent
        $key == pleft.key ? parent.left = left : parent.right = left
      else
        $root = left
      end
      left.parent = parent
    else
      if parent
        $key == parent.right.key ? parent.left = right : parent.right = right
      else
        $root = right
      end
      right.parent = parent
    end
  elsif $key < root.key
    delete left
  else
    delete right
  end
end
gets.to_i.times {
    command, $key = gets.split
    $key=$key.to_i
    case command
    when 'insert'
      insert
    when 'find'
      find $root
    when 'delete'
      delete $root
    else
      $root.inorder
      puts
      $root.preorder
      puts
    end
}