• + 0 comments

    scala

    import scala.io.StdIn
    import scala.util.Try
    
    
    object Solution {
      private final case class Tree(
          v: Int,
          l: Option[Tree] = None,
          r: Option[Tree] = None
      ) {
        def insert(i: Int): Tree = {
          if (i == v)
            throw new RuntimeException(s"$i already exists")
          if (i < v) {
            if (r.isDefined)
              throw new RuntimeException(s"invalid preorder at $i")
            this.copy(
              l = l
                .map(_.insert(i))
                .orElse(Option(Tree(i)))
            )
          } else
            this.copy(
              r = r
                .map(_.insert(i))
                .orElse(Option(Tree(i)))
            )
        }
      }
    
      def main(args: Array[String]): Unit = {
        val arr = Iterator
          .continually(StdIn.readLine())
          .takeWhile(null != _)
          .map(_.trim)
        val t = arr.next().toInt
        (1 to t)
          .map { _ =>
            arr.next()
            arr.next().split(' ').map(_.toInt)
          }
          .map(nodes =>
            Try(
              nodes.tail.foldLeft(Tree(nodes.head)) { case (tree, node) =>
                tree.insert(node)
              }
            ).map(_ => "YES")
              .getOrElse("NO")
          )
          .foreach(println)
      }
    }