Sort by

recency

|

11 Discussions

|

  • + 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)
      }
    }
    
  • + 0 comments

    I think its more important to stick with the basics of it. Because basics are more vital. If we can understand its basics this problem can be solved in matter of seconds.

  • + 0 comments

    Could someone pls point us to a javascript or python solution?....

  • + 0 comments

    F# solution with comment:

    open System
    
    let testBST input =
        let rec test input stack root =
            match input,stack with
            //whenever current number is smalller than root return false
            |(h::t),_ when h < root -> false
            //when top of stack is smaller then current number
            //make the top of stack the new root and pop the stack
            |(h::t),(x::s) when x < h -> test input s x 
            //if input is not empty and other states are not matched
            //push current number into stack
            |(h::t),_ -> test t (h::stack) root 
            //if all numbers a processed
            //means input is valid pre-order sequence of BST return true
            |[],_ -> true
            //if anything else happen throw an error
            |_ -> failwith "something goes wrong"
        test input [] -1
    
    [<EntryPoint>]
    let main argv =
        let num = Console.ReadLine()|>int
        let input = [
            for i in 1..num do
                //no need to know how many nodes in the tree so ignore it
                Console.ReadLine()|>ignore
                let temp = Console.ReadLine()
                yield temp.Split(" ")|>List.ofArray|>List.map(fun x -> x|>int)
        ]
        for i in input do
            if (testBST i) then printfn "%s" "YES"
            else printfn "%s" "NO"
        0 // return an integer exit code
    
  • + 0 comments

    Good approach is to just simulate preorder traversal. Since we know how the sequence is built we try to consume the elements in the order they are given to use. If the next element does not fit into our contraints of lo (lower bound) and hi (upper bound) then we propagate to the parent.

    As the result, running preorder on a valid sequence will consume all elements, otherwise if the sequence could not be fully consumed a non-empty sequence of the remaining elements will be returned.

    This could be easily mapped to YES/NO

    preorder [] lo hi = []
    preorder (x:xs) lo hi = if lo < x && x < hi then rest else x:xs
        where remain = preorder xs lo x
              rest = preorder remain x hi