This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
Unformatted text preview: Lists and Binary Trees (20 points) This problem uses the same datatype of trees as in Problem 4, but the trees are not binary search trees. Consider how to compute the sum of the values at each level of an int tree . For example, given the tree t shown below, level_sum t computes the list [3;4;5;4] . Here, 3 is the value at the root of the tree, 4 is the sum of integers at level 1, 5 is the sum of values at level 2, and the last 4 is the sum of the values at level 3. In general, the i th element of the list is the sum of values at the i th level of the tree (starting at i = 0 ). t : int tree = Level 0: 3> 3 / \ / \ Level 1: 2 2> 4 = (2 + 2) / \ / Level 2: 1 4> 5 = (0 + 1 + 4) \ Level 3: 4> 4 When thinking about how to implement level_sum , you created the following test code: let leaf (i:int) : int tree = Node(Empty, i, Empty) let t_left : int tree = Node(leaf 0, 2, leaf 1) let t_right : int tree = Node(Node(Empty, 4, leaf 4), 2, Empty) let t : int tree = Node(t_left, 3, t_right) let test () : bool = (level_sum Empty) = ;; run_test "level_sum Empty" test let test () : bool = (level_sum t_left) = [2; 1] ;; run_test "level_sum left subtree" test let test () : bool = (level_sum t_right) = [2; 4; 4] ;; run_test "level_sum right subtree" test let test () : bool = (level_sum t) = [3; 4; 5; 4] ;; run_test "example from diagram" test (Problem continues on next page.) 9 Implement the function level_sum by using the recursion pattern for binary trees. Hints: a. Decompose the problem into two functions: level_sum itself, and a helper function for use in combining the results of recursive calls to level_sum . b. The helper function should take two int list values as inputs and produce an int list . c. The test cases for t_left and t_right give the results of calling level_sum on the sub trees of t . Think about how to combine those results (using helper ) to get to the answer for level_sum t . let rec helper (l1:int list) (l2:int list) : int list = begin match (l1, l2) with  (_, ) > l1  (, _) > l2  (x::xs, y::ys) > (x+y)::(helper xs ys) end let rec level_sum (t:int tree) : int list = begin match t with  Empty >  Node(lt, x, rt) > let l1 = level_sum lt in let l2 = level_sum rt in x::(helper l1 l2) end Grading scheme: 20 points •1 point @, [x]:: •2 bad variable names •3 minor type error •3 wrong datatype •5 if rt=Empty —— lt=Empty then [n] •5 inexhaustive matches •5 no constructors •5 logic errors • other points at our discretion 10...
View
Full Document
 Spring '09
 Selfbalancing binary search tree, int list

Click to edit the document details