object Main extends App {
  val n: Int = io.StdIn.readInt()
  val bt: BTree = Empty

  (0 until n).foldLeft[BTree](bt){(t, _) =>
    val op: Array[String] = io.StdIn.readLine().split(" ")
    op(0) match {
      case "print" => t.show; t
      case "insert" => t.insert(op(1).toInt)
      case "find" => {
        val key: Int = op(1).toInt
        println(if (t.find(key)) "yes" else "no")
        t
      }
      case "delete" => {
        val key: Int = op(1).toInt
        t.delete(key)
      }
      case _ => throw new Error("Unknown operation")
    }
  }

  sealed trait BTree {
    def insert(x: Int): BTree
    def preorder: List[Int]
    def inorder: List[Int]
    def show: Unit = {
      println(" " + this.inorder.mkString(" "))
      println(" " + this.preorder.mkString(" "))
    }
    def find(x: Int): Boolean
    def delete(x: Int): BTree
    def leftmost: Int
  }
  case object Empty extends BTree {
    def insert(x: Int): BTree = Node(x, Empty, Empty)
    def preorder: List[Int] = Nil
    def inorder: List[Int] = Nil
    def find(x: Int): Boolean = false
    def delete(x: Int): BTree = this
    def leftmost: Int = throw new NoSuchElementException("error")
  }
  case class Node(v: Int, l: BTree, r: BTree) extends BTree {
    def insert(x: Int): BTree =
      if (x < v) Node(v, l.insert(x), r)
      else Node(v, l, r.insert(x))
    def preorder: List[Int] = v :: (l.preorder ::: r.preorder)
    def inorder: List[Int]  = l.inorder ::: (v :: r.inorder)
    def find(x: Int): Boolean =
      if (x == v) true
      else if (x < v) l.find(x)
      else r.find(x)
    def delete(x: Int): BTree = {
      if (x == v) {
        this match {
          case Node(_, Empty, Empty) => Empty
          case Node(_, _, Empty) => l
          case Node(_, Empty, _) => r
          case _ => {
            val n: Int = r.leftmost
            Node(n, l, r.delete(n))
          }
        }
      }
      else if (x < v) Node(v, l.delete(x), r)
      else Node(v, l, r.delete(x))
    }
    def leftmost: Int = l match {
      case Empty => v
      case _ => l.leftmost
    }
  }
}
