Tree: Preorder Traversal

  • + 0 comments

    Haskell

    It would have been nice if the problem statement gave an actual sample of the expected input data and how to parse it... Bad form, folks.

    module Main where
    
    data Tree = Empty | Node Int Tree Tree
    
    instance Show Tree where
        show Empty = ""
        show (Node x l r) =
            show x ++ " " ++ show l ++ show r
    
    insert :: Tree -> Int -> Tree
    insert Empty x = Node x Empty Empty
    insert (Node k left right) x
        | x < k = Node k (insert left x) right
        | otherwise = Node k left (insert right x)
    
    parseTree :: [Int] -> Tree
    parseTree = foldl insert Empty
    
    main :: IO ()
    main = do
        _ <- getLine
        seq <- map read . words <$> getLine :: IO [Int]
        print $ parseTree seq