Pabl0o0

Untitled

Nov 27th, 2017
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  1. module type TREE =
  2. sig
  3. type 'a bst_t
  4.  
  5. val create: unit -> 'a bst_t
  6. val push: 'a -> 'a bst_t -> 'a bst_t
  7. val find: 'a -> 'a bst_t -> bool
  8. (* val remove: 'a -> 'a bst_t *)
  9. val preorder: 'a bst_t -> 'a list
  10. val inorder: 'a bst_t -> 'a list
  11. end;;
  12.  
  13. module T : TREE =
  14. struct
  15. type 'a bst_t =
  16. | Leaf
  17. | Node of 'a bst_t * 'a * 'a bst_t (* Node (left, key, right) *)
  18. (* a node may also carry a data associated with the key.
  19. It is omitted here for neater demonstration *)
  20.  
  21. let create () = Leaf
  22.  
  23. let rec push x = function
  24. | Leaf -> Node (Leaf, x, Leaf) (* Leaf is a STOP *)
  25. | Node (left, k, right) ->
  26. if x < k then Node (push x left, k, right) (* if x is smaller, go left *)
  27. else Node (left, k, push x right) (* otherwise, go right *)
  28.  
  29. let rec find x = function
  30. | Leaf -> false
  31. | Node (left, k, right) ->
  32. if x < k then find x left
  33. else if x = k then true
  34. else find x right
  35.  
  36. let rec preorder = function
  37. | Leaf -> []
  38. | Node (l, v, r) -> v :: (preorder l @ preorder r)
  39.  
  40. let rec inorder = function
  41. | Leaf -> []
  42. | Node (l, v, r) -> inorder l @ (v :: inorder r)
  43. end;;
  44.  
  45. T.create()
  46. T.push(5)
  47. T.push(3)
  48. T.push(1)
  49. T.push(4)
  50. T.push(7)
  51.  
  52. T.find(3)
  53. T.preorder()
  54. T.inorder()
Advertisement
Add Comment
Please, Sign In to add comment