{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

midterm1-fall12-blank

Lists and binary trees 20 points this problem uses

Info iconThis preview shows pages 9–10. Sign up to view the full content.

View Full Document Right Arrow Icon
5. 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: 0 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
Background image of page 9

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

View Full Document Right Arrow Icon
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 = let rec level_sum (t: int tree) : int list = 10
Background image of page 10
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}