class Node
  attr_accessor :key, :parent, :left, :right

  def initialize(key)
    @key = key
    @parent = -1
    @left = nil
    @right = nil
  end

  def add_left(left)
    @left = left
    @left.parent = self
  end

  def add_right(right)
    @right = right
    @right.parent = self
  end

  def del_left; @left = nil; end

  def del_right; @right = nil; end

end


class BinaryTree
  attr_accessor :root

  def initialize()
    @root = nil
  end

  def insert(key)
    # 初回登録
    unless @root
      @root = Node.new(key)
      return
    end

    # 2回目以降
    #   xが挿入先にあたる. ので, nilになるまで探す.
    #   xの親がyで, yにadd_xxxxを実行する.
    x, y = @root, nil
    while x
      y = x
      if key < x.key
        x = x.left
      else
        x = x.right
      end
    end
    if key < y.key
      y.add_left(Node.new(key))
    else
      y.add_right(Node.new(key))
    end
  end

  def find(key)
    # keyがあった場合, 該当Nodeを返却
    # keyがなかった場合, nilを返却
    x = @root
    while x
      return x if x.key == key
      if key < x.key
        x = x.left
      else
        x = x.right
      end
    end
    nil
  end

  def delete(key)
    x = find(key)
    return unless x

    case
    when x.left && x.right # 子2
      self.in # 中間順探索で@listを更新
      nxt_i   = @list.index(x.key) + 1 # 削除する節の次の節のkeyを得るためのindex番号を取得
      nxt_key = find(@list[nxt_i]).key # 次の節のkeyを得る
      delete(nxt_key)
      x.key = nxt_key
    when x.left  # 子1
      replace(x, x.left)
    when x.right # 子1
      replace(x, x.right)
    else # 子0
      if x.parent.left == x
        x.parent.del_left
      else
        x.parent.del_right
      end
    end
  end

  def replace(from, to)
    if from.parent.left == from
      from.parent.add_left(to)
    else
      from.parent.add_right(to)
    end
  end

  def pre
    # 行きがけ順探索(左上から順に)
    @list = []
    traverse(@root, :pre)
    @list
  end

  def in
    # 通りがけ順探索
    @list = []
    traverse(@root, :in)
    @list
  end

  def post
    # 帰りがけ順探索(左下から順に)
    @list = []
    traverse(@root, :post)
    @list
  end

  private
  def traverse(node, type)
    @list << node.key if type == :pre
    traverse(node.left, type) if node.left
    @list << node.key if type == :in
    traverse(node.right, type) if node.right
    @list << node.key if type == :post
  end
end


n = gets.to_i
cmds = []
n.times do
  stdin = gets.chomp
  if stdin.match(/print/)
    cmds << [stdin, nil]
  else
    cmd, key = stdin.split
    cmds << [cmd, key.to_i]
  end
end

tree = BinaryTree.new
cmds.each do | cmd, key |
  if cmd.match(/insert/)
    tree.insert(key)
  elsif cmd.match(/find/)
    puts tree.find(key) ? 'yes' : 'no'
  elsif cmd.match(/delete/)
    tree.delete(key)
  else
    puts " #{tree.in.join(' ')}"
    puts " #{tree.pre.join(' ')}"
  end
end
