Tree: Inorder Traversal

  • + 0 comments

    Haskell

    module Main where
    
    data Tree a = Empty | Node a (Tree a) (Tree a) deriving (Show)
    
    inOrder :: Tree a -> [a]
    inOrder Empty = []
    inOrder (Node a left right) = inOrder left ++ [a] ++ inOrder right
    
    insertNode :: (Ord a) => Tree a -> a -> Tree a
    insertNode Empty x = Node x Empty Empty
    insertNode (Node a left right) x
        | x < a = Node a (insertNode left x) right
        | x > a = Node a left (insertNode right x)
        | otherwise = Node a left right
    
    main :: IO ()
    main =
        interact $
            unwords . map show . inOrder . foldl insertNode Empty . map (read :: String -> Int) . words . (!! 1) . lines