Advertisement
karlicoss

BST :)

Jul 4th, 2011
755
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show)
  2.  
  3. {- constructors -}
  4. treeByList :: (Ord a) => [a] -> Tree a
  5. treeByList x = foldr treeInsert EmptyTree x
  6. {--}
  7.  
  8.  
  9. printTreeHelper :: (Show t) => Tree t -> Int -> [Char]
  10. printTreeHelper EmptyTree margin                    = ""
  11. printTreeHelper (Node a EmptyTree EmptyTree) margin = (replicate margin ' ') ++ (show a)
  12. printTreeHelper (Node a left right) margin          = (replicate margin ' ') ++ (show a) ++ "\n" ++ (printTreeHelper left (margin + 3)) ++ "\n" ++  (printTreeHelper right (margin + 3))
  13.  
  14. printTree :: (Show t) => Tree t -> [Char]
  15. printTree a = printTreeHelper a 0
  16.  
  17. {- methods -}
  18. inTree :: (Ord a) => a -> Tree a -> Bool
  19. inTree _ EmptyTree = False
  20. inTree x (Node a left right)
  21.     | x == a  = True
  22.     | x < a   = inTree x left
  23.     | x > a   = inTree x right
  24.  
  25. treeInsert :: (Ord a) => a -> Tree a -> Tree a
  26. treeInsert x EmptyTree = (Node x EmptyTree EmptyTree)
  27. treeInsert x (Node a left right)
  28.     | x == a = Node a left right
  29.     | x > a  = Node a left (treeInsert x right)
  30.     | x < a  = Node a (treeInsert x left) right
  31.  
  32. treeGetMin :: (Ord a) => Tree a -> a
  33. treeGetMin (Node a EmptyTree right) = a
  34. treeGetMin (Node a left right) = treeGetMin left
  35.  
  36. treeErase :: (Ord a) => a -> Tree a -> Tree a
  37. treeErase x EmptyTree = EmptyTree
  38. treeErase x (Node a left right)
  39.     | x > a = (Node a left (treeErase x right))
  40.     | x < a = (Node a (treeErase x left) right)
  41. treeErase x (Node a EmptyTree right)     = right
  42. treeErase x (Node a left EmptyTree)      = left
  43. treeErase x (Node a left right)          = Node (treeGetMin right) left (treeErase (treeGetMin right) right)
  44. {--}
  45.  
  46.  
  47. elems = [7, 5, 3, 1, 6, 2, 4]
  48.  
  49. mytree = treeByList elems
  50.  
  51. main = putStrLn $ printTree (foldr treeErase mytree [4, 3, 2])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement