This preview has intentionally blurred sections. Sign up to view the full version.View Full Document
Unformatted text preview: | Empty -> Node(Empty, n, Empty) | Node(lt, x, rt) -> if x = n then t else if n < x then Node (insert lt n, x, rt) else Node(lt, x, insert rt n) end a. (5 points) Circle the trees that satisfy the binary search tree invariant . (Note that we have omitted the Empty nodes from these pictures.) (a) (b) (c) (d) (e) 4 3 2 3 7 \ / \ / \ \ \ 5 2 6 1 6 6 6 \ / \ / \ \ 6 5 4 2 7 5 \ \ 7 4 Answer: (a), (b) b. (8 points) For each definition below, circle the letter of the tree above that it constructs or “none of the above”. Grading Scheme: 4 points per answer let t1 : int tree = Node(Node(Empty, 1, Empty), 2, Node(Empty, 6, (Node (Empty, 4, Empty)))) (a) (b) (c) (d) (e) none of the above Answer: (c) let t2 : int tree = insert (insert (insert (insert Empty 4) 5) 6) 7 (a) (b) (c) (d) (e) none of the above Answer: (a) let t3 : int tree = insert (insert (insert (insert Empty 2) 5) 3) 6 8 (a) (b) (c) (d) (e) none of the above Answer: none of the above let t4 : int tree = Node(Empty, 3, Node(Node (Empty, 2, Empty), 6, (Node (Empty, 7, Empty)))) (a) (b) (c) (d) (e) none of the above Answer: (d) c. (15 points) Complete the definition of a function bst_separate that, when given an integer x, separates a binary search tree into two parts. The first part should contain the values less than x, the second part should contain the values greater than or equal to x. For example, when given the binary search tree t 5 / \ 3 6 / \ 4 the result of bst_separate 5 t is the pair of binary search trees: 3 5 / \ and \ 4 6 Your solution must take advantage of the binary search tree invariant to avoid traversing the entire tree and should not refer to any of the bst operations such as insert , remove , and inorder . (Use the next page for your implementation.) 9 let rec bst_separate (x:int) (t : int tree) : int tree * int tree = begin match t with | Empty -> (Empty, Empty) | Node (l, y, r) -> if x = y then (l, Node (Empty, y, r)) else if x < y then let (l1, l2) = bst_separate x l in (l1, Node (l2, y, r)) else let (r1, r2) = bst_separate x r in (Node (l, y, r1), r2) Grading Scheme: • no deduction for minor syntax errors • rough allocation of points: 2 for empty case, 3 for equality case, 5 for < case, and 5 for > case. •-3 recursive calls to *both* left and right subtrees (not using invariant) •-2 (each) missing single recursive call to left or right subtree •-2 (each) not reforming correct tree after recursive call, using the node data constructor •-2 for swapping < and > cases •-1 for missing x argument in recursive call •-1 for not saving result of recursive call to local variable (i.e. recomputing bst_separate twice as much as necessary) • other errors at discretion 10...
View Full Document
- Spring '09
- INSERT, University of Pennsylvania, int list, val generic_separate