Created
December 27, 2016 20:52
-
-
Save ygrenzinger/fd289967bba60ad5a5da19a36d880cfb to your computer and use it in GitHub Desktop.
chapter11-BinaryTree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module C where | |
data BinaryTree a = Leaf | |
| Node (BinaryTree a) a (BinaryTree a) | |
deriving (Eq, Ord, Show) | |
insert' :: Ord a => a -> BinaryTree a -> BinaryTree a | |
insert' e Leaf = Node Leaf e Leaf | |
insert' e (Node left n right) | |
| e == n = Node left e right | |
| e < n = Node (insert' e left) n right | |
| e > n = Node left n (insert' e right) | |
mapTree :: (a -> b) -> BinaryTree a -> BinaryTree b | |
mapTree _ Leaf = Leaf | |
mapTree f (Node left n right) = Node (mapTree f left) (f n) (mapTree f right) | |
preorder :: BinaryTree a -> [a] | |
preorder Leaf = [] | |
preorder (Node left n right) = [n] ++ preorder left ++ preorder right | |
inorder :: BinaryTree a -> [a] | |
inorder Leaf = [] | |
inorder (Node left n right) = preorder left ++ [n] ++ preorder right | |
postorder :: BinaryTree a -> [a] | |
postorder Leaf = [] | |
postorder (Node left n right) = preorder right ++ [n] ++ preorder left | |
foldTree :: (a -> b -> b) -> b -> BinaryTree a -> b | |
foldTree f acc = foldr f acc . inorder | |
t1 :: BinaryTree Integer | |
t1 = insert' 10 Leaf | |
t2 :: BinaryTree Integer | |
t2 = insert' 3 t1 | |
t3 :: BinaryTree Integer | |
t3 = insert' 13 t2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment