open Assert open Trees open TreeExamples (* This file is available if you would like to *) (* play around with BSTs. In particular, try to *) (* implement the insert and delete functions without *) (* looking at the lecture notes! *) ;; stop_on_failure () (***********************) (* BINARY SEARCH TREES *) (***********************) let lec07_tree : tree = Node(Node(leaf 0, 1, leaf 3), 5, Node(Empty, 7, Node(leaf 8, 9, Empty))) (* 5 *) (* / \ *) (* 1 7 *) (* / \ \ *) (* 0 3 9 *) (* / *) (* 8 *) ;; print_endline "===========================" ;; print_endline "Example binary-search tree" ;; print_endline (string_of_tree lec07_tree) (* Determines whether t contains n *) let rec lookup (t: tree) (n: int) : bool = begin match t with | Empty -> false | Node (lt, x, rt) -> x == n || if n < x then lookup lt n else lookup rt n end let test () : bool = lookup lec07_tree 9 ;; run_test "lookup 9" test let test () : bool = not (lookup lec07_tree 12) ;; run_test "lookup 12" test (* helper functions for writing is_bst (tree_less t n) is true when all *) (* nodes of t are strictly less than n *) let rec tree_less (t: tree) (n: int) : bool = begin match t with | Empty -> true | Node(lt,x,rt) -> x < n && (tree_less lt n) && (tree_less rt n) end (* (tree_gtr t n) is true when all nodes of t are strictly greater than n *) let rec tree_gtr (t: tree) (n: int) : bool = begin match t with | Empty -> true | Node(lt,x,rt) -> n < x && (tree_gtr lt n) && (tree_gtr rt n) end (* determines whether t satisfies the binary search tree invariant *) let rec is_bst (t: tree) : bool = begin match t with | Empty -> true | Node(lt,x,rt) -> is_bst lt && is_bst rt && (tree_less lt x) && (tree_gtr rt x) end let test() : bool = is_bst lec07_tree ;; run_test "is_bst" test let test() : bool = not (is_bst (Node (leaf 5, 2, leaf 3))) ;; run_test "not is_bst" test (* Inserts n into the binary search tree t *) let rec insert (t: tree) (n: int) : tree = failwith "insert: unimplemented" let test () : bool = contains (insert Empty 3) 3 ;; run_test "insert 3" test let test () : bool = contains (insert lec07_tree 4) 4 ;; run_test "insert 4" test let test () : bool = inorder (insert lec07_tree 4) = [0;1;3;4;5;7;8;9] ;; run_test "inorder insert 4" test (* returns the maximum integer in a *NONEMPTY* binary search tree t *) let rec tree_max (t: tree) : int = failwith "tree_max" let test () : bool = tree_max lec07_tree = 9 ;; run_test "tree_max" test (* returns a binary search tree that has the same set of nodes as t except *) (* with n removed (if it's there) *) let rec delete (t: tree) (n: int) : tree = failwith "delete" let test () : bool = inorder (delete lec07_tree 3) = [0;1;5;7;8;9] ;; run_test "delete 3" test let test () : bool = inorder (delete lec07_tree 9) = [0;1;3;5;7;8] ;; run_test "delete 9" test let test () : bool = inorder (delete lec07_tree 1) = [0;3;5;7;8;9] ;; run_test "delete 1" test