Tree: Postorder Traversal

  • + 0 comments

    Haskell

    module Main where
    
    data Tree = Empty | Node Int Tree Tree
    
    instance Show Tree where
        show Empty = ""
        show (Node x l r) =
            show l ++ show r ++ show x ++ " "
    
    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