Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

preorder, postorder, foldTree, mapTree for binary trees #57

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions src/BinaryTree/BinarySearchTree.hs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,17 @@ nodeKey (Node x _ _) = Just x

-- Perform inorder walk of the binary search tree.
-- Cormen, Thomas H., et al. Introduction to algorithms. pg. 288, MIT press, 2009.
inorderWalk :: (Eq a, Ord a) => BTree a -> [a]
inorderWalk Empty = []
inorderWalk (Node x l r) = (inorderWalk l) ++ [x] ++ (inorderWalk r)
inorder :: (Eq a, Ord a) => BTree a -> [a]
inorder Empty = []
inorder (Node x l r) = inorder l ++ [x] ++ inorder r

preorder :: BTree a -> [a]
preorder Empty = []
preorder (Node a left right) = a : preorder left ++ preorder right

postorder :: BTree a -> [a]
postorder Empty = []
postorder (Node a left right) = postorder left ++ postorder right ++ [a]

-- Function to insert a value into the tree. Returns the new tree.
-- Cormen, Thomas H., et al. Introduction to algorithms. pg. 294, MIT press, 2009.
Expand Down
15 changes: 14 additions & 1 deletion src/BinaryTree/BinaryTree.hs
Original file line number Diff line number Diff line change
Expand Up @@ -68,4 +68,17 @@ numNodes t = length $ bfsList t
-- Pretty Print a Binary Tree
simplePrint :: (Show a) => BTree a -> String
simplePrint Empty = ""
simplePrint t = (nodeShow t) ++ " " ++ (simplePrint $ getLeftTree t) ++ (simplePrint $ getRightTree t)
simplePrint t = (nodeShow t) ++ " " ++ (simplePrint $ getLeftTree t) ++ (simplePrint $ getRightTree t)

foldTree :: (a -> b -> b) -> b -> BTree a -> b
foldTree f acc Empty = acc
foldTree f acc (Node a left right) = foldTree f foldedRightSubtree left where
result = f a acc
foldedRightSubtree = foldTree f result right

mapTree :: (a -> b) -> BTree a -> BTree b
mapTree _ Empty = Empty
mapTree f (Node a left right) = Node (f a) left' right' where
left' = mapTree f left
right' = mapTree f right