data Tree a = Leaf | Node a (Tree a) (Tree a) deriving (Show, Eq) tr1 :: Tree Int tr1 = Node 5 (Node 4 Leaf Leaf) (Node 6 (Node 7 Leaf Leaf) Leaf) mapTree :: (a -> b) -> Tree a -> Tree b mapTree f Leaf = Leaf mapTree f (Node x l r) = Node (f x) (mapTree f l) (mapTree f r) foldTree :: (a -> b -> b -> b) -> b -> Tree a -> b foldTree f x Leaf = x foldTree f x (Node y l r) = f y (foldTree f x l) (foldTree f x r) height :: Tree a -> Int height Leaf = 0 height (Node x l r) = if height l > height r then height l + 1 else height r + 1 height' :: Tree a -> Int height' tr = foldTree (\ x l r -> if l > r then l+1 else r+1) 0 tr nodes :: Tree a -> Int nodes Leaf = 0 nodes (Node x l r) = 1 + nodes l + nodes r nodes' :: Tree a -> Int nodes' tr = foldTree (\ x l r -> 1 + l + r) 0 tr depthFirst :: Tree a -> [a] depthFirst Leaf = [] depthFirst (Node x l r) = depthFirst l ++ [x] ++ depthFirst r tr2 :: Tree Int tr2 = Node 8 (Node 9 (Node 5 Leaf Leaf) (Node 6 Leaf Leaf)) (Node 7 Leaf Leaf) helper :: [Tree a] -> [a] helper [] = [] helper (Leaf:xs) = helper xs helper ((Node y l r):xs) = y : helper (xs ++ [l, r]) helper' :: [Tree a] -> [a] helper' [] = [] helper' (x:xs) = case x of Leaf -> helper' xs Node y l r -> y : helper' (xs ++ [l, r]) breadthFirst :: Tree a -> [a] breadthFirst tr = helper' [tr] my_lookup :: [(Int, a)] -> Int -> a my_lookup [] k = error "doesn't exist" my_lookup ((x, y):xs) k = if k == x then y else my_lookup xs k my_lookup' :: [(Int, a)] -> Int -> Maybe a my_lookup' [] k = Nothing my_lookup' ((x, y):xs) k = if k == x then Just y else my_lookup' xs k