Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- object Solution extends App {
- val n = readInt
- //recommended
- def isBST(curNodes: List[Int]): Boolean = {
- curNodes match {
- case root :: Nil => true
- case Nil => true
- case root :: nodes =>
- val leftNodeIndex = nodes.indexWhere(_ < root)
- val rightNodeIndex = nodes.indexWhere(_ > root)
- val leftNodes = if (leftNodeIndex < 0) Nil else if (rightNodeIndex > 0) nodes.slice(leftNodeIndex, rightNodeIndex) else nodes.slice(leftNodeIndex, curNodes.size - 1)
- val rightNodes = if (rightNodeIndex < 0) Nil else nodes.slice(rightNodeIndex, curNodes.size - 1)
- !leftNodes.exists(_ > root) && isBST(leftNodes) && !rightNodes.exists(_ < root) && isBST(rightNodes)
- case _ => false
- }
- }
- // (1 to n).map(i => readLine.split(" ").map(_.toInt).sum).foreach(println)
- (1 to n).foreach { i =>
- readLine
- println(if(isBST(readLine.split(" ").map(_.toInt).toList)) "YES" else "NO")
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement