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

    def initialize(key, parent)
      @key = key
      @parent = parent
    end
  end

  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

    return 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
    return 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
    return 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
    return node
  end

  def delete_helper(node)
    if node.left && node.right
      next_node_index = inorder_helper(node.right).first
      next_node = find(next_node_index)

      copied = copy_node(node, next_node.key)
      node.right.parent = copied
      node.left.parent = copied
      replace(node, copied)
      delete_helper(next_node)
      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.push(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 = gets.chomp.to_i
n.times do
  command, param = gets.chomp.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