lec11 - (* Binary search tree, each node has value and two...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
(* Binary search tree, each node has value and two children. * * For any node with value x, all the values in the left * subtree are smaller than x, and all those in the right * subtree are larger than x (using built-in < as comparator). *) type 'a tree = TNode of 'a * 'a tree * 'a tree | TLeaf t let rec contains x = function TLeaf -> false | TNode (y, l, r) -> if x=y then true else if x < y then contains x l else contains x r let rec add x = function TLeaf -> TNode (x, TLeaf, TLeaf) (* When get to leaf, put new node there *) | TNode (y, l, r) as t -> (* Recursively search for value *) if x=y then t else if x > y then TNode (y, l, add x r) else (* x < y *) TNode (y, add x l, r) let rec depth = function TLeaf -> 0 | TNode(_, a, b) -> 1+max (depth a) (depth b) let rec tree_of_list = function [] -> TLeaf | x :: l -> add x (tree_of_list l) a (* fold_inorder f acc t folds the function f over the tree t, * going left subtree, current value, right subtree *) let rec fold_inorder f acc t = match t with TLeaf -> acc | TNode(v,l,r) -> let acc = fold_inorder f acc l in let acc = f acc v in fold_inorder f acc r (* Check that a binary search tree is ordered: for a node * with value x the left subtree has values < x and the * right subtree has values > x *) (* Returns the minimum value in t, max_int if t is empty *) let findmin_int t = let f acc v = if v<acc then v else acc in fold_inorder f max_int t (* Returns the maximum value in t, min_int if t is empty *) let findmax_int t =
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
let f acc v = if v>acc then v else acc in fold_inorder f min_int t (* Check that: 1. Maximum of the left subtree is less than the current value 2. Minimum of the right subtree is greater than the current value 3. Left subtree is a valid BST 4. Right subtree is a valid BST Note: We implicitly require uniqueness of values Note: Empty subtrees always satisfy requirements 1 and 2 *) let rec repOk_int t = match t with TLeaf -> true | TNode(v,l,r) -> let (lmax,rmin) = (findmax_int l, findmin_int r) in
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 6

lec11 - (* Binary search tree, each node has value and two...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online