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

Similar documents
Data Structure and Algorithm Homework #6 Due: 5pm, Friday, June 14, 2013 TA === Homework submission instructions ===

Algorithm Design and Analysis Homework #2 Due: 2:20pm, Thursday, October 17, 2013 TA

Data Structure and Algorithm Homework #2 Due: 2:00pm, Thursday, March 29, 2012 TA

Data Structure and Algorithm Homework #5 Due: 2:00pm, Thursday, May 31, 2012 TA === Homework submission instructions ===

6.1 Skip List, Binary Search Tree

Data Structure and Algorithm Homework #1 Due: 1:20pm, Tuesday, March 21, 2017 TA === Homework submission instructions ===

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

Writeup for first project of CMSC 420: Data Structures Section 0102, Summer Theme: Threaded AVL Trees

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

Data Structure and Algorithm, Spring 2013 Midterm Examination 120 points Time: 2:20pm-5:20pm (180 minutes), Tuesday, April 16, 2013

Operations on Heap Tree The major operations required to be performed on a heap tree are Insertion, Deletion, and Merging.

CS134 Spring 2005 Final Exam Mon. June. 20, 2005 Signature: Question # Out Of Marks Marker Total

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

CS 171: Introduction to Computer Science II. Binary Search Trees

CS251-SE1. Midterm 2. Tuesday 11/1 8:00pm 9:00pm. There are 16 multiple-choice questions and 6 essay questions.

Algorithm Design and Analysis Homework #4

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

ECE264 Spring 2013 Final Exam, April 30, 2013

Data Structure and Algorithm Homework #3 Due: 1:20pm, Thursday, May 16, 2017 TA === Homework submission instructions ===

Problem Set 6 Due: 11:59 Sunday, April 29

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

R10 SET - 1. Code No: R II B. Tech I Semester, Supplementary Examinations, May

Lecture 5. Treaps Find, insert, delete, split, and join in treaps Randomized search trees Randomized search tree time costs

Data Structures and Algorithms (DSA) Course 9 Lists / Graphs / Trees. Iulian Năstac

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

CSE 373 OCTOBER 11 TH TRAVERSALS AND AVL

CS301 - Data Structures Glossary By

R10 SET - 1. Code No: R II B. Tech I Semester, Supplementary Examinations, May

Computer Science Foundation Exam

12 Abstract Data Types

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

COMP251: Algorithms and Data Structures. Jérôme Waldispühl School of Computer Science McGill University

CSCI2100B Data Structures Trees

Data Structure and Algorithm Midterm Reference Solution TA

Algorithms. AVL Tree

CSE 332, Spring 2010, Midterm Examination 30 April 2010

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

Data and File Structures Laboratory

MLR Institute of Technology

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

INF2220: algorithms and data structures Series 1

EE 368. Weeks 5 (Notes)

8. Binary Search Tree

CSE 100 Advanced Data Structures

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

Algorithms in Systems Engineering ISE 172. Lecture 16. Dr. Ted Ralphs

Computer Science Foundation Exam. Dec. 19, 2003 COMPUTER SCIENCE I. Section I A. No Calculators! KEY

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

Data Structures and Algorithms

Chapter 20: Binary Trees

MULTIMEDIA COLLEGE JALAN GURNEY KIRI KUALA LUMPUR

EECE.2160: ECE Application Programming

CSE100. Advanced Data Structures. Lecture 8. (Based on Paul Kube course materials)

CS261: HOMEWORK 2 Due 04/13/2012, at 2pm

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

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

CP2 Revision. theme: dynamic datatypes & data structures

Trees, Part 1: Unbalanced Trees

TREES Lecture 12 CS2110 Spring 2019

FINALTERM EXAMINATION Fall 2009 CS301- Data Structures Question No: 1 ( Marks: 1 ) - Please choose one The data of the problem is of 2GB and the hard

V Advanced Data Structures

Binary Trees and Binary Search Trees

Binary Search Trees. Contents. Steven J. Zeil. July 11, Definition: Binary Search Trees The Binary Search Tree ADT...

Fall, 2015 Prof. Jungkeun Park

Homework Assignment #3

Programming and Data Structures Prof. N.S. Narayanaswamy Department of Computer Science and Engineering Indian Institute of Technology, Madras

Data Structures Question Bank Multiple Choice

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

CS2110 Assignment 3 Inheritance and Trees, Summer 2008

Trees. Eric McCreath

Homework #4 RELEASE DATE: 04/22/2014 DUE DATE: 05/06/2014, 17:30 (after class) in CSIE R217

Computer Science Foundation Exam

MIDTERM EXAM (HONORS SECTION)

Trees (Part 1, Theoretical) CSE 2320 Algorithms and Data Structures University of Texas at Arlington

Solution to CSE 250 Final Exam

The time and space are the two measure for efficiency of an algorithm.

V Advanced Data Structures

Data Structures Lesson 7

Data Structure. IBPS SO (IT- Officer) Exam 2017

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

BINARY SEARCH TREES cs2420 Introduction to Algorithms and Data Structures Spring 2015

Computer Science Foundation Exam

CSE373: Data Structures & Algorithms Lecture 5: Dictionary ADTs; Binary Trees. Linda Shapiro Spring 2016

Data Structure - Advanced Topics in Tree -

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

FORTH SEMESTER DIPLOMA EXAMINATION IN ENGINEERING/ TECHNOLIGY- OCTOBER, 2012 DATA STRUCTURE

MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct.

CMPT 225. Lecture 6 linked list

Largest Online Community of VU Students

Computational Optimization ISE 407. Lecture 16. Dr. Ted Ralphs

Binary Search Trees. Analysis of Algorithms

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

DATA STRUCTURE : A MCQ QUESTION SET Code : RBMCQ0305

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

CSI 402 Spring 2014 Programming Assignment I 1 / 15

INSTITUTE OF AERONAUTICAL ENGINEERING

CS102 Binary Search Trees

CSE 373 APRIL 17 TH TREE BALANCE AND AVL

ENEE 150: Intermediate Programming Concepts for Engineers Spring 2018 Handout #27. Midterm #2 Review

CS302 Data Structures using C++

Transcription:

Data Structure and Algorithm Homework #3 Due: 2:20pm, Tuesday, April 9, 2013 TA email: dsa1@csientuedutw === Homework submission instructions === For Problem 1, submit your source code, a Makefile to compile the source, and a brief documentation to the SVN server (katrinacsientuedutw) You should create a new folder hw3 and put these three files in it The filenames of the source code, Makefile, and the documentation file should be mainc, Makefile, and reporttxt, respectively; you will get some penalties in your grade if your submission does not follow the naming rule The documentation file should be in plain text format (txt file) In the documentation file you should explain how your code works, and anything you would like to convey to the TAs For Problem 2 through 5, submit the answers via the SVN server (electronic copy) or to the TA at the beginning of class on the due date (hard copy) Except the programming assignment, each student may only choose to submit the homework in only one way; either all in hard copies or all via SVN If you submit your homework partially in one way and partially in the other way, you might only get the score of the part submitted as hard copies or the part submitted via SVN (the part that the grading TA chooses) If you choose to submit the answers of the writing problems through SVN, please combine the answers of all writing problems into only ONE file in the pdf format, with the file name in the format of hw3 [student ID]pdf (eg hw3 b01902888pdf ); otherwise, you might only get the score of one of the files (the one that the grading TA chooses) Discussions with others are encouraged However, you should write down your solutions by your own words In addition, for each problem you have to specify the references (the Internet URL you consulted with or the people you discussed with) on the first page of your solution to that problem NO LATE SUBMISSION IS ALLOWED for the homework submission in hard copies - no score will be given for the part that is submitted after the deadline For submissions via SVN (including the programming assignment and electronic copies of the writing problems), up to one day of delay is allowed; however, the score of the part that is submitted after the deadline will get some penalties according to the following rule (the time will be in seconds): LATE SCORE = ORIGINAL SCORE (1 DelayT ime/86400) 1

Problem 1 k-dimensional Tree (30%) In computer science, a k-d tree (short for k-dimensional tree) is a space-partitioning data structure for organizing points in a k-dimensional space k-d trees are useful data structures for several applications A common application of k-d tree is to find the nearest point to a specific point (See Figure 1 for an example) In addition, the data structure supports point insertion or deletion operations In this homework, you are asked to implement k-d tree for the k = 1 case, and the data structure should support the operations of querying the nearest point, point insertion, and point deletion nearest point distance = 2 Figure 1: Nearest point searching in 2-dimensional space The dots are existing points on the plane and the cross is the point to which we are trying to find the nearest point Note that the point to which we are asked to find the nearest point does not need to be one of existing points on the plane A 1-d tree (k-d tree with k = 1) is just a simple binary search tree A point in the 1-d space, ie, on a number line, corresponds to a node in the binary search tree The insertion (deletion) of points to (from) current set of points corresponds to inserting (deleting) nodes to (from) the current binary search tree As an example, Figure 2 shows a few points on the number line and the corresponding 1-d tree 4 7 5 1 5 4 1 7 Figure 2: Points on the number line and the corresponding 1-d tree, which is also a binary search tree Finding the nearest point out of a set of existing points P to a specific point is similar to searching for a node, X, in the binary search tree The only difference is that, in the process 2

of finding the nearest point, if X in the corresponding binary search tree cannot be found, the closest node found in the tree (corresponding to the closest point) should be reported In other words, if X is not found, we are looking for a node Y such that the absolute difference between X and Y is the minimum, ie, Y = arg min X y, y P Since the tree is a binary search tree, we y only have to check the nodes that we have gone through in the process of finding X See Figure 3 for an example 50 5 60 1 7 6 24 30 9 15 11 17 Figure 3: This figure illustrates how to search for the closest node in a 1-d tree The nodes that we have visited when we search for node 11 are 50, 5, 7, 24,, 15 The closest one to 11 is, and it is the nearest point since its absolute difference to 11 is = 11 = 1 and is the minimum Your program will be tested with the test data in the following format The first line in the input is a positive integer N, which represents the number of operations in the input Each of the following N lines specifies one of the 3 types of operations below For convenience, we call a point with coordinate x on the number line as point x Assume that the set of points P is initially empty All numbers in the input are integers insert x : Add point x to the current set P It is guaranteed that point x will not be in P before the insertion delete x : Delete point x from current set P It is guaranteed that point x is in P before the deletion query x : Find the nearest point in P to point x and output its coordinate If there are multiple points in P with the same minimum distance to x, output all of them in ascending order It is guaranteed that there will be at least one point in P before the query You may assume that the test data is generated randomly That is, your binary search tree will not become too unbalanced even if you do all insertions from the test data sequentially 3

Input example 7 insert 4 insert insert 5 query 7 delete 5 query 7 query Output example 5 4 When performing the first query, the set of points is {4, 5, }, in which 5 is the nearest one to 7 When performing the second query, the set of points is {4, }, in which both 4 and are the nearest points to 7 When performing the third query, since is in the current set, the nearest point is itself Please use main as the filename of your main program 4

Problem 2 A Piece of Graph (20%) Let G = (V, E) be an undirected graph Prove the following statements: 21 (5%) If we sum up the degrees of all vertices in G, the answer must be an even number 22 (5%) If we can find two vertices u, v V such that there are two different paths from u to v, then G must contain a cycle 23 (5%) If for any two vertices u, v V there is exactly one path from u to v, then G is a tree (Hint: recall that a tree is a connected graph with no cycle) 24 (5%) If G is a connected graph with n vertices, then G must have at least n 1 edges Problem 3 Tree Traversal Orders (15%) 31 (5%) A max binary tree is a binary tree in which the key value of each node is no smaller than the key values of its children (if it has any) Given the in-order traversal sequence of a max binary tree, please derive and draw the tree in-order: 7, 31, 32, 9, 15, 3, 38, 21, 23, 13, 37, 25, 18, 30, 34, 26 32 (5%) Given the pre-order traversal sequence of a binary search tree, please derive and draw the tree pre-order: 16, 5, 1, 9, 8,, 11, 36, 29, 24, 23, 27, 25, 32, 38, 40 33 (5%) Convert the binary search tree in the previous problem into a in-order threaded binary tree and draw the tree Please specify the type of each link in the tree, ie, whether it is a thread or an ordinary tree edge You also have to draw the dummy node and its links in the tree 5

Problem 4 Merge Binary Search Trees (20%) After learning the properties and the operations of binary search tree (BST), let s try to work on a more advanced problem You are given two complete BST, ie, a BST that is also a complete binary tree, and are asked to merge them into one BST Assume that T ree 1 has N nodes and T ree 2 has M nodes, and all nodes in both trees have distinct key values The structure of a node is shown in the following code 1 struct node { 2 int value ; 3 struct node * left ; 4 struct node * right ; 5 }; 6 typedef struct node Node ; Figure 4: Insertion of nodes in T ree 1 in pre-order to T ree 2 6

41 (5%) A simple algorithm is given in the following, implementing the procedures shown in Figure 4 The algorithm performs pre-order traversal on T ree 1 and, in each time it visits a node, it inserts the node to T ree 2 using the ordinary BST insertion operation Please give the time complexity of this algorithm in terms of N and M using the big-oh notation and make sure this bound is as tight as possible 1 Node * insert ( Node * tree2, int value ){ 2 if( tree2 == NULL ){ 3 Node * newnode = ( Node *) malloc ( sizeof ( Node )); 4 newnode - > value = value ; 5 return newnode ; 6 } 7 if( value < tree2 -> value ) 8 tree2 -> left = insert ( tree2 ->left, value ); 9 else tree2 -> right = insert ( tree2 -> right, value ); return tree2 ; 11 } 12 13 Node * mergetree1 ( Node * tree1, Node * tree2 ){ 14 if( tree1 == NULL ) return tree2 ; 15 tree2 = insert ( tree2, tree1 -> value ); 16 mergetree1 ( tree1 ->left, tree2 ); 17 mergetree1 ( tree1 -> right, tree2 ); 18 return tree2 ; 19 } 7

42 (15%) We are not satisfied the previous algorithm, since it is not only inefficient in some cases but also prone to the unbalanced problem Thus, we will propose an algorithm that includes the following steps: (a) Convert the two BSTs into two sorted arrays with in-order traversals (b) Merge the two sorted array into one (c) Convert the merged sorted array into a BST which has the minimum height (Hint: One solution is to take the middle element in the sorted array as the root of the final BST, then treat the elements on the left as the nodes in the left subtree of the root and the elements on the right as the right subtree of the root Perform the same operation to all subtrees recursively) The implementation of this algorithm in C is shown in the function merget ree2 below But all inner functions are unfinished Please copy and complete the skeleton code of inner functions and make sure that merget ree2 runs in O(N + M) time overall Show the running time of each of the functions you implemented and from there show that the overall running time is indeed O(N + M) The skeleton of the inner functions is shown in the next page You can treat N and M as constant integers and use them in your code directly 1 Node * mergetree2 ( Node * tree1, Node * tree2 ){ 2 if( tree1 == NULL ) return tree2 ; 3 if( tree2 == NULL ) return tree1 ; 4 5 int * array1 = ( int *) malloc (N* sizeof ( int )); 6 int * array2 = ( int *) malloc (M* sizeof ( int )); 7 int * sortedarray = ( int *) malloc ((N+M)* sizeof ( int )); 8 9 array1 = treetoarray ( tree1, array1 ); array2 = treetoarray ( tree2, array2 ); 11 sortedarray = mergearray ( array1, array2, sortedarray ); 12 Node * tree = arraytotree ( sortedarray, N + M); 13 14 free ( array1 ); 15 free ( array2 ); 16 free ( sortedarray ); 17 18 return tree ; 19 } 8

1 / 2 int treetoarray(node, int ); 3 Give a root of a BST and an initialized array, 4 return the sorted array which is converted from BST 5 / 6 int * treetoarray ( Node * tree, int * array ){ 7 if( tree == NULL ) return array ; 8 int * head = array ; 9 //TODO add some statements here 11 return head ; 12 } 13 14 / 15 int mergearray(int, int, int ); 16 Give two sorted arrays and an initialized array, 17 return the sorted array which is merged from them 18 / 19 int * mergearray ( int * array1, int * array2, int * array ){ 20 int * sortedarray = array ; 21 //TODO add some statements here 22 23 return sortedarray ; 24 } 25 26 / 27 int arraytotree(int, int); 28 Give a sorted array and its size, 29 return the root of BST which is converted from array 30 / 31 Node * arraytotree ( int * array, int size ){ 32 if( size == 0) return NULL ; 33 Node * node = ( Node *) malloc ( sizeof ( Node )); 34 //TODO add some statements here 35 36 return node ; 37 } 9

Problem 5 Linked-Lists and Trees (15%) After over 20 hours of coding, Michael has just finished his DSA homework in time, in which he implemented a sorted descending circular doubly linked-list as the data structure to perform some complicated operations that are specified in the homework description by the Professor It is now one hour before the deadline He decides to go ahead and submit the homework via SVN However, when reading the submission guidelines again, he finds that there is a small line of words at the bottom: Please use a heap or a BST to implement the operations in this homework He is shocked and has no idea how to finish this homework in time There is no time to re-write the program from scratch The only feasible solution he can come up with is to find the functions to convert linked-lists to heaps and BSTs Luckily, the C structure defined for a doubly linked-list node and a tree node is exactly the same - the node of either data structure includes a data portion and two pointers Nodes of doubly linked-lists have the previous and next pointers while the tree nodes have left-child and right-child pointers The prototype of function and the C structure of the node is shown as follows: 1 struct node { 2 int index ; 3 struct node * prev ; //Should be the left child ptr in tree 4 struct node * next ; //Should be the right child ptr in tree 5 }; 6 struct node * link_ lst_ to_ heap ( struct node * head ); 51 (5%) Linked-lists to heaps (using the linked tree representation, not the array representation shown in the lecture) Please design an algorithm to covert a circular doubly linked-list to a heap in O(N) time You are allowed to use a few extra pointers but not allowed to use extra nodes, ie, no malloc operations 52 (%) Linked-lists to BSTs (a) Please design an algorithm to convert a circular doubly linked-list to a binary search tree in O(N) time You are allowed to use a few extra pointers but not allowed to use extra nodes, ie, no malloc operations (Hint: the BST can be extremely unbalanced, but it is still a BST :-P ) (b) In certain cases, the BST produced from the algorithm in the previous question may have very poor query performance We would like to convert it to a balanced BST, where the depths of the two subtrees of every node differ by 1 or less More definitions on wiki can be found:

http://enwikipediaorg/wiki/binary tree In this case, the depth of the tree would be minimized You are asked to design an algorithm to recursively operate on the descending circular doubly linked-list and convert it to a balanced BST in O(N log N) time Same as before, you are allowed to use a few extra pointers but not allowed to use extra nodes, ie, no malloc operations 53 (bonus 5%) Please take a look at the description of a data structure called skip-list, http://enwikipediaorg/wiki/skip list and explained how it works and what is the time complexity of the operation of building a balanced binary search tree from a circular doubly linked-skip-list 11