-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathvalid-bst.hs
More file actions
27 lines (22 loc) · 742 Bytes
/
valid-bst.hs
File metadata and controls
27 lines (22 loc) · 742 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
{-
Valid BST (https://www.hackerrank.com/challenges/valid-bst)
FP/Functional Structures, Medium, 20 pts
Given a list of numbers, determine whether it can represent the preorder
traversal of a binary search tree (BST).
-}
import Control.Monad
validTree :: [Int] -> Bool
validTree [] = True
validTree (x:xs) = validTree left && validTree right && rightOk
where
left = takeWhile (<=x) xs
right = dropWhile (<=x) xs
rightOk = if not $ null right then minimum right > x else True
main :: IO ()
main = do
t <- fmap (read::String->Int) getLine
forM_ [1..t] $ \_ -> do
n <- fmap (read::String->Int) getLine
a <- getLine
let as = map (read::String->Int) $ words a
putStrLn $ if validTree as then "YES" else "NO"