final-fa12-solutions

# Combine base sum d size c isfull none none preorder h

This preview shows pages 15–17. Sign up to view the full content.

combine base sum d 0 size c 0 is_full none none preorder h or i [] postorder f [] inorder g [] Your choices for combine and base are enumerated below. Write the choice a–j for the combine function and the choice a–j for base . If no choice works ( i.e. the function cannot be expressed as a fold) write “none” in both slots. You may use the same choice more than once. Combine choices: Base choices: (a) ( fun x lv rv -> Node(rv, x, lv)) (b) ( fun x lv rv -> lv + rv) (c) ( fun x lv rv -> lv + 1 + rv) (d) ( fun x lv rv -> lv + x + rv) (e) ( fun x lv rv -> (size lv) = (size rv)) (f) ( fun x lv rv -> [email protected]@[x]) (g) ( fun x lv rv -> [email protected][x]@rv) (h) ( fun x lv rv -> [x]@[email protected]) (i) ( fun x lv rv -> x::[email protected]) (j) ( fun x lv rv -> [email protected]@x) (a) true (b) false (c) 0 (d) 1 (e) Empty (f) [] (g) [x] (h) lv (i) rv 15

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

View Full Document
(20 points) This problem uses the same OCaml type of trees as in Problem 6, repeated here for your reference: type ’a tree = | Empty | Node of (’a tree) * ’a * (’a tree) a. State the binary search tree invariant in words. We have done the case for Empty trees: The Empty tree is a binary search tree. The tree Node(lt, x, rt) is a binary search tree if and only if: lt and rt are both binary search trees and x is greater than all values in lt and less than all values in rt . Rubric: 5 pts.: 2 pts. for lt and rt are both bsts. 3 pts for less-than and greater-than constrainta b. Write an OCaml function range that, given an integer binary search tree t and integers low and hi such that low < hi , returns the list of BST nodes such that low <= x <= hi (in sorted order). For example, range t 1 6 would yield [1;2;3;5] when t is the tree to the right. Use the binary search tree invariant to avoid processing more of the tree than necessary. If you need help remembering OCaml syntax, see the examples in problem 6. 3 / \ / \ 1 8 / \ / 0 2 5 \ 7 ( * Assumes: t is a binary search tree * ) let rec range (t:int tree) (low:int) (hi:int) : int list = begin match t with | Empty -> [] | Node(lt,x,rt) -> if then (range lt low hi) @ [x] @ (range rt low hi) else if x < low then range rt low hi else range lt low hi end Rubric: 15 pts. 3 pts for base case 5 pts for x is in range and recursive calls 7 pts for using invariant to search when x is not in range 16