You are viewing a single comment's thread. Return to all 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) } }
Seems like cookies are disabled on this browser, please enable them to open this website
Valid BST
You are viewing a single comment's thread. Return to all comments →
scala