You must print this PDF and write your answers neatly by hand. You should hand in the assignment before recitation begins.

Similar documents
The assignment is due by 1:30pm on Tuesday 5 th April, 2016.

You must include this cover sheet. Either type up the assignment using theory5.tex, or print out this PDF.

Lecture Notes on Binary Search Trees

Lecture 18 Restoring Invariants

Lecture 15 Notes Binary Search Trees

Lecture Notes on Binary Search Trees

Midterm 2 Exam Principles of Imperative Computation. Tuesday 31 st March, This exam is closed-book with one sheet of notes permitted.

Midterm II Exam Principles of Imperative Computation Frank Pfenning. March 31, 2011

You must print this PDF and write your answers neatly by hand. You should hand in the assignment before recitation begins.

CSE 332 Autumn 2013: Midterm Exam (closed book, closed notes, no calculators)

Lecture Notes on Binary Search Trees

Lecture Notes on Priority Queues

CSE 332 Spring 2013: Midterm Exam (closed book, closed notes, no calculators)

Lecture 15 Binary Search Trees

CSE 373 Spring 2010: Midterm #1 (closed book, closed notes, NO calculators allowed)

CSE 373 Autumn 2010: Midterm #1 (closed book, closed notes, NO calculators allowed)

Lecture Notes on Binary Search Trees

CSE 332 Spring 2014: Midterm Exam (closed book, closed notes, no calculators)

You must include this cover sheet. Either type up the assignment using theory3.tex, or print out this PDF.

CSE 332 Winter 2015: Midterm Exam (closed book, closed notes, no calculators)

Module 4: Index Structures Lecture 13: Index structure. The Lecture Contains: Index structure. Binary search tree (BST) B-tree. B+-tree.

CSE373 Fall 2013, Midterm Examination October 18, 2013

Lecture 17 Priority Queues

Lecture 17 Notes Priority Queues

8. Binary Search Tree

CSE 373 Winter 2009: Midterm #1 (closed book, closed notes, NO calculators allowed)

Trees. (Trees) Data Structures and Programming Spring / 28

Section 4 SOLUTION: AVL Trees & B-Trees

Print out this PDF double-sided, staple pages in order, and write your answers on these pages neatly.

You must include this cover sheet. Either type up the assignment using theory4.tex, or print out this PDF.

DATA STRUCTURES AND ALGORITHMS. Hierarchical data structures: AVL tree, Bayer tree, Heap

CS 315 Data Structures mid-term 2

Section 1: True / False (1 point each, 15 pts total)

! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge

! Tree: set of nodes and directed edges. ! Parent: source node of directed edge. ! Child: terminal node of directed edge

CS301 - Data Structures Glossary By

University of Illinois at Urbana-Champaign Department of Computer Science. Second Examination

Tree: non-recursive definition. Trees, Binary Search Trees, and Heaps. Tree: recursive definition. Tree: example.

9. Heap : Priority Queue

Computer Science 210 Data Structures Siena College Fall Topic Notes: Priority Queues and Heaps

Fall, 2015 Prof. Jungkeun Park

Data Structures and Algorithms

Binary Trees. Directed, Rooted Tree. Terminology. Trees. Binary Trees. Possible Implementation 4/18/2013

Lecture 16 Notes AVL Trees

/633 Introduction to Algorithms Lecturer: Michael Dinitz Topic: Priority Queues / Heaps Date: 9/27/17

Recall: Properties of B-Trees

Balanced Search Trees. CS 3110 Fall 2010

Midterm I Exam Principles of Imperative Computation Frank Pfenning. February 17, 2011

: Principles of Imperative Computation. Summer Assignment 4. Due: Monday, June 11, 2012 in class

: Fundamental Data Structures and Algorithms. June 06, 2011 SOLUTIONS

Algorithms. AVL Tree

Sorted Arrays. Operation Access Search Selection Predecessor Successor Output (print) Insert Delete Extract-Min

BINARY HEAP cs2420 Introduction to Algorithms and Data Structures Spring 2015

Lesson 21: AVL Trees. Rotation

Data Structure and Algorithm Homework #3 Due: 2:20pm, Tuesday, April 9, 2013 TA === Homework submission instructions ===

Chapter 6 Heapsort 1

Priority Queues Heaps Heapsort

Uses for Trees About Trees Binary Trees. Trees. Seth Long. January 31, 2010

Exam I Principles of Imperative Computation, Summer 2011 William Lovas. May 27, 2011

CS102 Binary Search Trees

Lecture 16 AVL Trees

Analysis of Algorithms

Test #2. Login: 2 PROBLEM 1 : (Balance (6points)) Insert the following elements into an AVL tree. Make sure you show the tree before and after each ro

Most of this PDF is editable. You can either type your answers in the red boxes/lines, or you can write them neatly by hand.

Trees. A tree is a directed graph with the property

Some Search Structures. Balanced Search Trees. Binary Search Trees. A Binary Search Tree. Review Binary Search Trees

Binary heaps (chapters ) Leftist heaps

Final Exam Principles of Imperative Computation Frank Pfenning, Tom Cortina, William Lovas. December 10, Name: Andrew ID: Section:

Binary Trees, Binary Search Trees

CS171 Final Practice Exam

Note that this is a rep invariant! The type system doesn t enforce this but you need it to be true. Should use repok to check in debug version.

CS24 Week 8 Lecture 1

Chapter 20: Binary Trees

MLR Institute of Technology

How much space does this routine use in the worst case for a given n? public static void use_space(int n) { int b; int [] A;

Topic: Heaps and priority queues

: Principles of Imperative Computation, Spring Homework 3 Theory [Update 1]

COSC 2007 Data Structures II Final Exam. Part 1: multiple choice (1 mark each, total 30 marks, circle the correct answer)

Dictionaries. Priority Queues

CSE 332, Spring 2010, Midterm Examination 30 April 2010

- 1 - Handout #22S May 24, 2013 Practice Second Midterm Exam Solutions. CS106B Spring 2013

CSCI2100B Data Structures Heaps

Most of this PDF is editable. You can either type your answers in the red boxes/lines, or you can write them neatly by hand.

Prepared By: Ms. Nidhi Solanki (Assist. Prof.) Page 1

Binary Trees and Binary Search Trees

Quiz 1 Solutions. (a) f(n) = n g(n) = log n Circle all that apply: f = O(g) f = Θ(g) f = Ω(g)

University of Illinois at Urbana-Champaign Department of Computer Science. Second Examination

Print out this PDF double-sided, staple pages in order, and write your answers on these pages neatly.

Recitation 9. Prelim Review

COS 226 Midterm Exam, Spring 2009

Fibonacci Heaps Priority Queues. John Ross Wallrabenstein

Second Examination Solution

INF2220: algorithms and data structures Series 1

This is a set of practice questions for the final for CS16. The actual exam will consist of problems that are quite similar to those you have

CSE 250 Final Exam. Fall 2013 Time: 3 hours. Dec 11, No electronic devices of any kind. You can open your textbook and notes

Properties of a heap (represented by an array A)

Binary Heaps. COL 106 Shweta Agrawal and Amit Kumar

Comparisons. Θ(n 2 ) Θ(n) Sorting Revisited. So far we talked about two algorithms to sort an array of numbers. What is the advantage of merge sort?

Lec 17 April 8. Topics: binary Trees expression trees. (Chapter 5 of text)

Sample Exam 1 Questions

Transcription:

15-122 Homework 5 Page 1 of 15 15-122 : Principles of Imperative Computation, Summer 1 2014 Written Homework 5 Due: Thursday, June 19 before recitation Name: Andrew ID: Recitation: Binary search trees, AVL trees, heaps, priority queues, and more heaps. Question Points Score 1 10 2 7 3 8 4 4 5 6 Total: 35 You must print this PDF and write your answers neatly by hand. You should hand in the assignment before recitation begins.

15-122 Homework 5 Page 2 of 15 Part I: High Up in a Tree For questions 1 and 2, we define the height of a tree as the number of nodes on the longest path between the root and a leaf, inclusive. For example, the empty tree has height 0, a tree with 1 node has height 1, and a balanced tree with 3 nodes has height 2. 1. Binary Search Trees (1) (a) Draw the binary search tree that results from inserting the following keys in the order given. Be sure all branches in your tree are drawn clearly so we can distinguish left branches from right branches. 75, 92, 99, 13, 84, 42, 71, 98, 73, 20 (1) (b) How many different binary search trees can be constructed using the following five keys if they can be inserted in any order? 73, 28, 52, 9, 104

15-122 Homework 5 Page 3 of 15 (c) For the following questions, you should refer to the implementation of binary search trees discussed in class. The code is available on the course website. (3) i. Write the function bst_height which returns the height of the given BST, as per the definition given on page 2. Your function must include a recursive helper function tree_height. (Hint: the height of a tree is one more than the height of its deepest subtree.) int tree_height(tree* T) //@requires is_ordered(t, NULL, NULL); int bst_height(bst B) //@requires is_bst(b); //@ensures is_bst(b); return ; (1) ii. Complete the code for the function largest_child which removes and returns the largest child rooted at a given tree node T. elem largest_child(tree* T) //@requires T!= NULL && T->right!= NULL; if (T->right->right == NULL) elem e = ; T->right = ; return e; return largest_child( );

15-122 Homework 5 Page 4 of 15 (4) iii. Consider extending the BST library implementation with the following function which deletes an element from the tree with the given key. void bst_delete(bst B, key k) //@requires is_bst(b); //@ensures is_bst(b); B->root = tree_delete(b->root, key k); Complete the code for the recursive helper function tree_delete which is used by the bst_delete function. This function should return a pointer to the tree rooted at T once the key is deleted (if it is in the tree). tree* tree_delete(tree* T, key k) if (T == NULL) // key is not in the tree return ; if (key_compare(k, elem_key(t->data)) < 0) = tree_delete(t->left, k); return T; else if (key_compare(k, elem_key(t->data)) > 0) = tree_delete(t->right, k); return T; else // key is in current tree node T if (T->left == NULL) return ; else if (T->right == NULL) return ; else // continued on next page...

15-122 Homework 5 Page 5 of 15 // T has two children if (T->left->right == NULL) // Replace T s data with the left child s data. ; // Replace the left child with its left child. ; return T; else // Search for the largest child in the // left subtree of T and replace the data // in node T with this data after removing // the largest child in the left subtree. T->data = largest_child(t->left); return T;

15-122 Homework 5 Page 6 of 15 2. AVL Trees. (3) (a) Insert the following values into an initially empty AVL tree one at a time in the order shown. Draw the final state of the AVL tree after each insert is completed and the tree is restored back to its proper invariants (do not draw the intermediate steps of any rebalancing operations). Your answer should show exactly 7 clearly drawn trees. 89, 79, 45, 58, 10, 63, 31

15-122 Homework 5 Page 7 of 15 (b) We want to determine upper and lower bounds on the number of nodes in an AVL tree of a certain height. Let m(h) be the minimum number of nodes in a valid AVL tree of height h. Let M(h) be similarly defined for the maximum number of nodes. (2) i. Fill in the table below relating the values h and m(h): h m(h) 0 0 1 1 2 2 3 4 5 6 (1) ii. Guided by the table in part (i), complete the recursive definition of m(h). The base cases have been completed for you. (Hint: think Fibonacci.) m(h) = 0 if h = 0 1 if h = 1 if h 2 (1) iii. Give a closed form expression for M(h). M(h) =

15-122 Homework 5 Page 8 of 15 3. Piles of Theory Part II: Heaps of Work As discussed in class, a min-heap is a hierarchical data structure that satisfies two invariants: Order: Every child has value greater than or equal to its parent. Shape: Each level of the min-heap is completely full except possibly the last level, which has all of its elements stored as far left as possible. (Also known as a complete binary tree). Consider: (1) (a) Draw a picture of the final state of the min-heap after an element with value 5 is inserted. Be sure to satisfy both of the data structure invariants for a min-heap. (1) (b) Starting from the original min-heap above, draw a picture of the final state of the min-heap after the element with the minimum value is deleted. Be sure to satisfy both of the data structure invariants for a min-heap.

15-122 Homework 5 Page 9 of 15 (2) (c) Insert the following values into an initially empty min-heap one at a time in the order shown. Draw the final state of the min-heap after each insert is completed and the min-heap is restored back to its proper invariants. Your answer should show 8 clearly drawn heaps. 42, 19, 71, 38, 20, 6, 55, 10

15-122 Homework 5 Page 10 of 15 (1) (d) Assume a heap is stored in an array as discussed in class. Using the final min-heap from your previous answer, show where each element would be stored in the array. You may not need to use all of the array positions shown below. (1) (e) You are given a non-empty min-heap. In one sentence, describe precisely where the maximum value must be located. Do not assume the heap is implemented as an array. (Your vocabulary should pertain only to the tree definition of a heap). (1) (f) What is the worst-case runtime complexity of finding the maximum in a min-heap if the min-heap has n elements? Why? O( ) Because the number of values that need to be examined is: (1) (g) We are given an array A of n integers. Consider the following sorting algorithm: Insert every integer from A into a min-heap. Repeatedly delete the minimum from the heap, storing the deleted values back into A from left to right. What is the worst-case runtime complexity of this algorithm, using Big-O notation? Briefly explain your answer. O( )

15-122 Homework 5 Page 11 of 15 4. Jumbles of Code Refer to the implementation of heaps discussed in class that is available on our course website. (2) (a) Add a meaningful assertion about H to each of the functions below. void pq_insert(heap H, elem e) //@requires is_heap(h) &&!pq_full(h); //@ensures is_heap(h); H->data[H->next] = e; (H->next)++; //@assert ; int i = H->next - 1; while (i > 1 && priority(h, i) < priority(h, i/2)) //@loop_invariant 1 <= i && i < H->next; //@loop_invariant is_heap_except_up(h, i); swap(h->data, i, i/2); i = i/2; //@assert is_heap(h); return; elem pq_delmin(heap H) //@requires is_heap(h) &&!pq_empty(h); //@ensures is_heap(h); int n = H->next; elem min = H->data[1]; H->data[1] = H->data[n-1]; H->next = n-1; if (H->next > 1) //@assert ; sift_down(h, 1); return min;

15-122 Homework 5 Page 12 of 15 (1) (b) Complete the function pq_max, that returns (but does not remove) the element with the maximum value from a min-heap stored as an array. You should examine only those elements that might contain the maximum. elem heap_max(heap H) //@requires is_heap(h) &&!pq_empty(h); //@ensures is_heap(h); int max = ; for (int i = ; i < ; i++) if (priority(h, i) > priority(h, max)) max = i; return ;

15-122 Homework 5 Page 13 of 15 (1) (c) The library function pq_build, shown below, takes an array of data elements (ignoring index 0 of the array) and builds our array-based min-heap in place. That is, it uses the given array inside of the heap structure rather than allocating a new array. heap pq_build(elem[] E, int n) //@requires 0 < n && n <= \length(e); //@ensures is_heap(\result); heap H = alloc(struct heap_header); H->limit = n; H->next = 1; H->data = E; for (int i = 1; i < n; i++) pq_insert(h, E[i]); return H; This code disrespects the boundary between the client and the library. Complete the function build_broken_heap below such that the postcondition will always succeed. heap build_broken_heap(int[] E, int n) //@requires 3 <= n && n <= \length(e); //@ensures!is_heap(\result); heap H = pq_build(e, n); E[1] = ; E[2] = ; return H;

15-122 Homework 5 Page 14 of 15 5. Priority Queues (4) (a) You are working an exciting desk job as a stock market analyst. You want to be able to determine the total sum value of all of the top stocks at any time. However, since the year is 1983, your Commodore 64 can only offer up about 30 KB of memory. Stock reports are delivered to you via a stream data type with the following interface: struct stock_report string company; int value; // stock value in whole dollars ; typedef struct stock_report* report; // Retrieve the next stock report from the data stream report get_report(stream S); // Returns true if the data stream is empty bool stream_empty(stream S); A stream of stock reports could be very, very large. Storing all of the reports in an array won t cut it you don t have enough memory (30 KB isn t even enough to store 2000 reports). You ll need a more clever solution. Luckily, your cubicle mate Jim just finished a stellar heap implementation with the interface below. You think you should be able to use Jim s priority queue to keep track of only the largest stock reports, discarding the smaller ones as necessary. // Client Interface typedef elem; int elem_priority(elem e) /*@requires e!= NULL; @*/; // Library Interface typedef pq; pq pq_new(int capacity) /*@requires capacity > 0; @*/; bool pq_full(pq Q); bool pq_empty(pq Q); void pq_insert(pq Q, elem e) /*@requires!pq_full(q) && e!= NULL; @*/; elem pq_delmin(pq Q) /*@requires!pq_empty(q); @*/; elem pq_min(pq Q) /*@requires!pq_empty(q); @*/; Complete the function total_value on the next page, which returns the sum of the values of the top n reports from the data stream S (by top reports, we mean those with the largest monetary value). Oh, and don t forget to implement the client interface for the priority queue!

15-122 Homework 5 Page 15 of 15 typedef elem; int elem_priority(elem e) return ; int total_value(stream S, int n) pq Q = pq_new( ); while (!stream_empty(s)) // Put the next stock report into the priority queue // If the priority queue is at capacity, delete the // report with the smallest value if ( ) // Add up the values of all reports in the priority queue int total = 0; while ( ) total += ; return total; (2) (b) When does a priority queue behave like a stack? (Hint: think about how priorities must be assigned to elements that are inserted into the priority queue.)