Solutions Manual. Data Structures and Algorithms in Java, 5th edition. M. T. Goodrich and R. Tamassia

Size: px
Start display at page:

Download "Solutions Manual. Data Structures and Algorithms in Java, 5th edition. M. T. Goodrich and R. Tamassia"

Transcription

1 Solutions Manual Data Structures and Algorithms in Java, 5th edition M. T. Goodrich and R. Tamassia

2 Chapter 1 Reinforcement Solution R-1.3 Since, after the clone, A[4] and B[4] are both pointing to the same GameEntry object, B[4].score is now 550. Solution R-1.7 for (int i=1; i<=58; i++) { wallet[0].chargeit((double)i); wallet[1].chargeit(2.0*i); wallet[2].chargeit((double)3*i); This change will cause credit card 2 to go over its limit. Solution R-1.10 public boolean ismultiple(long n, long m) { if (n%m == 0) return true; else return false; Solution R-1.12 public integer sumton(integer N) { if (n == 1) return 1; else return (n 1 + sumton(n 1)); Creativity Solution C-1.3 public boolean alldistinct( int[ ] ints ) { for( int i = 0; i < ints.length 1; i++ ) // we don t need to test numbers at indices already checked for (int j = i+1; j < ints.length; j++) if (ints[i]==ints[j]) return false; return true; 1

3 import java.util.vector; public class CharPermutation{ private void Permute( Vector bag, Vector permutation ) { // When the bag is empty, a full permutation exists if( bag.isempty() ) { System.out.println( permutation ); else { // For each element left in the bag for( int i = 0; i < bag.size(); i++ ) { // Take the element out of the bag // and put it at the end of the permutation Character c = (Character) bag.elementat( i ); bag.removeelementat( i ); permutation.addelement( c ); // Permute the rest of the bag this.permute( bag, permutation ); // Take the element off the permutation // and put it back in the bag permutation.removeelementat( permutation.size() 1 ); bag.insertelementat( c, i ); Solution C-1.5 Here is a possible solution: 2

4 public void PrintPermutations( char[ ] elements ) { Vector bag = new Vector(); Vector permutation = new Vector(); for( int i = 0; i < elements.length; i++ ) { bag.addelement( new Character( elements[i] ) ); this.permute( bag, permutation ); public static void main( String[ ] args ) { char[ ] elements = { c, a, r, b, o, n ; new CharPermutation().PrintPermutations( elements ); Solution C-1.7 class ArraySizeException extends Exception { public ArraySizeException() { super(); public ArraySizeException( String s ) { super( s ); public int[] compute( int[ ] a, int[] b ) throws ArraySizeException { if( a.length!= b.length ) { throw new ArraySizeException( "arrays must have same length" ); int[ ] c = new int[a.length]; for( int i = 0; i < a.length; i++ ) { c[i]= a[i] * b[i]; return c; 3

5 Chapter 2 Reinforcement Solution R-2.1 There are two immediate inefficiencies: (1) the chaining of constructors implies a potentially long set of method calls any time an instance of a deep class, Z, is created, and (2) the dynamic dispatch algorithm for determining which version of a certain method to use could end up looking through a large number of classes before it finds the right one to use. Solution R-2.2 Whenever a large number of classes all extend from a single class, it is likely that you are missing out on potential code reuse from similar methods in different classes. There is likely some factoring of methods into common classes that could be done in this case, which would save programmer time and maintenance time, by eliminating duplicated code. Solution R-2.4 Air traffic control software, computer integrated surgery applications, and flight navigation systems. Solution R calls to nextvalue will end on the value Since the maximum positive value of a long is , calls to nextvalue can be made before a long-integer overflow. Solution R-2.11 No, d is referring to a Equestrian object that is not not also of type Racer. Casting in an inheritance relationship can only move up or down the hierarchy, not sideways. Creativity Solution C-2.1 This is written as multiple lines, but it is really one line of code: class P{public static void main(string[]a){string p= class P{public static void main(string[]a){string p=%c%s%c;system.out.printf(p,34,p,34); ; System.out.printf(p,34,p,34); Solution C-2.4 Inheritance in Java allows for specialized classes to be built from generic classes. Because of this progression from generic to specialized in the class hierarchy, there can never be a circular pattern of inheritance. In other words, there cannot be a superclass A and derived classes B and C such that B extends A, then C extends B, and finally A extends C. Such a cycle is impossible because A is the generic superclass from which C is eventually extended, thus it is impossible from A to extend C, for this would mean A is extending itself. Therefore, there can never occur a circular relationship which would cause an infinite loop in the dynamic dispatch. 4

6 Chapter 3 Reinforcement Solution R-3.3 Add a statement, n ; in the remove method and add a statement, n++; in the add method. Solution R-3.7 The alpha array and the ALPHASIZE value would have be changed to the new alphabet and its size. In addition, all the places that use the literal A to refer to the first letter would now have to be changed to the first letter in the new alphabet. In this case, it would be better to define a final static int FIRSTLETTER, define it to the first letter, and use it instead of A. This assumes the messages are still in upper-case, of course. Solution R-3.10 Create a new node with next pointing to head. Set head pointing to the new node. Creativity Solution C-3.2 The product will be 0 with probability , which is much larger than 0.99, since the only way the product will not be zero is if no element of A is zero. Solution C-3.5 Sort the array B then scan it from front to end looking for the repeated entries. Each pair of repeated integers will be consecutive in the sorted listing. Solution C-3.6 Define an (n+1) (n+1) two-dimensional Boolean array M, which will record the meeting pairs. So that M[i, j] = true if and only if player i and j have meet. In addition, define a one-dimensional integer array c of size n+1 so that c[i] is a count of the number of other players that player i has met. When a player i and j meet, we check M[i, j], and if it is true, then we are done the players have already met. Otherwise, we set M[i, j] and M[ j,i] to true and we increment c[i] and c[ j]. If either of c[i] or c[ j] equal n 1 after this, then we have a winner. Solution C-3.7 The recursive algorithm, product(n, m), for computing product using only addition and subtraction, is as follows: If m = 1 return n. Otherwise, return n plus the result of a recursive call to the method product with parameters n and m 1. 5

7 Solution C-3.8 Let us define a method reverse(l,n), which reverses the first n L.size() nodes in L, and returns a pointer end to the node just after the nth node in L (end = null if n = L.size()). If L.size() 1, we are done, so let us assume L has at least 2 nodes. If n = 1, then we return L.first().next(). Otherwise, we recursively call reverse(l,n 1), and let end denote the returned pointer to the nth node in L. We then set ret to end.next() if n < L.size(), and to null otherwise. We then insert the node pointed to by end at the front of L and we return ret. The total running time is O(n). Solution C-3.9 Simply use a temporary node to walk to the end of list L. Then, make the last element of L point to the first element of M as its next node. Concatenate() Create a new node v v = L.getHead() while v! = null do v = V.getNext() v.setnext(m.gethead()) L = L The number of steps is proportional to the size of L. Solution C-3.10 Use two temporary Node elements, temp1 and temp2. Initialize temp1 to be the trailer node of L and temp2 to be the header node of M. Make the element of temp1 have its next field point to temp2 and set the element of temp2 to have its prev field point to temp1. Set L to be L and then set the trailer node of L to be the trailer node of M. Solution C-3.15 To count the number of nodes using a recursive method, numnodes(node N), which takes a Node as a parameter and returns an integer, we simply do the following. To begin, numnodes is given the header node of the list. Regardless, numnodes checks to see if the parameter N is null. If so, it returns 0. Otherwise, it returns 1 plus the result of numnodes with input N.getNext(). Solution C-3.23 Let p be the cursor for L and let q be the cursor for M. Perform a traversal around L. At each node visited, check if this node is q. 6

8 Chapter 4 Reinforcement Solution R-4.7 Setting the two equations equal and simplifying, we see that the cross-over occurs at n = 4logn. Now, we can confirm that the cross-over occurs at n = 2 4 = 16. Solution R-4.8 Setting the two sides equal and simplifying confirms that the cross-over occurs at n = 20. That is, 40n 2 2n 3 for n 20. Solution R-4.9 The constant function. Solution R-4.10 It is because logn c = clogn. Solution R-4.11 If this sum is E(n), then it is clearly equal to 2S(n), where S(n) is the sum of all integers from 1 to n; hence, E(n) = n(n+1). Solution R-4.12 If c f(n) is an upper bound on the running time, for some constant c, for all inputs, then this must also be an upper bound on the worst-case time. Solution R ,2 logn,3n+100logn,4n,nlogn,4nlogn+2n,n n,n 3,2 n Solution R-4.14 There are constants c and n 0 such that d(n) c f(n) for n n 0. Thus, ad(n) ac f(n) for n n 0. Solution R-4.15 We have, by definition that d(n) c 1 f(n) for n n 1, and e(n) c 2 g(n) for n n 2. Thus, for n max{n 1,n 2, d(n)e(n) c 1 f(n)e(n) c 1 c 2 f(n)g(n). Solution R-4.16 The Ex1 method runs in O(n) time. 7

9 Solution R-4.17 The Ex2 method runs in O(n) time. Solution R-4.18 The Ex3 method runs in O(n 2 ) time. Solution R-4.19 The Ex4 method runs in O(n) time. Solution R-4.20 The Ex5 method runs in O(n 3 ) time. Solution R-4.21 The worst case running time of find2d is O(n 2 ). This is seen by examining the worst case where the element x is the very last item in the n n array to be examined. In this case, find2d calls the algorithm arrayfind n times. arrayfind will then have to search all n elements for each call until the final call when x is found. Therefore, n comparisons are done for each arrayfind call. Since arrayfind is called n times, we have n n operations, or an O(n 2 ) running time. But the size, N, of A is n 2, so this is also O(N)-time algorithm. Thus, this is actually a linear-time algorithm, since its running time is equal to a linear function of the input size. Solution R-4.22 The numbers in the first row are quite large. The table below calculates it approximately in powers of 10. People might also choose to use powers of 2. Being close to the answer is enough for the big numbers (within a few factors of 10 from the answers shown). 1 Second 1 Hour 1 Month 1 Century logn n nlogn n n n Solution R-4.29 By the definition of big-oh, we need to find a real constant c > 0 and an integer constant n 0 1 such that (n+1) 5 c(n 5 ) for every integer n n 0. Since (n+1) 5 = n 5 + 5n n n 2 + 5n+1, (n+1) 5 c(n 5 ) for c = 8 and n n 0 = 2. 8

10 Solution R-4.30 By the definition of big-oh, we need to find a real constant c > 0 and an integer constant n 0 1 such that 2 n+1 c(2 n ) for n n 0. One possible solution is choosing c = 2 and n 0 = 1, since 2 n+1 = 2 2 n. Solution R-4.31 n nlogn for n 2 (but this is not true for n = 1). Solution R-4.33 By the definition of big-omega, we need to find a real constant c > 0 and an integer constant n 0 1 such that nlogn cn for n n 0. Choosing c = 1 and n 0 = 2, shows nlogn cn for n n 0, since logn > 1 in this range. Solution R-4.38 The running time of Algorithm D is proportional to n i=1 i, which is O(n2 ). Solution R-4.39 To say that Al s algorithm is big-oh of Bill s algorithm implies that Al s algorithm will run faster than Bill s for all input greater than some nonzero positive integer n 0. In this case, n 0 = 100. Creativity Solution C-4.3 Assuming we have all three sets stored in arrays, combine all three arrays into one array. Next, sort this combined array and look to see if any element is repeated three times. If so, the three original sets are not disjoint. Solution C-4.5 The solution makes use of the function FindPair(A, i, j, k) below, which given the sorted subarray A[i.. j] determines whether there is any pair of elements that sums to k. First it tests whether A[i]+ A[ j] < k. Because A is sorted, for any j j, we have A[i] + A[ j ] < k. Thus, there is no pair involving A[i] that sums to k, and we can eliminate A[i] and recursively check the remaining subarray A[i+1.. j]. Similarly, if A[i]+A[ j] > k, we can eliminate A[ j] and recursively check the subarray A[i.. j 1]. Otherwise, A[i]+A[ j] = k and we return true. If no such pair is ever found, eventually all but one element is eliminated (i = j), and we return false. Solution C-4.7 Since r is represented with 100 bits, any candidate p that the eavesdropper might use to try to divide r uses also at most 100 bits. Thus, this very naive algorithm requires divisions, which would take about 2 80 seconds, or at least 2 55 years. Even if the eavesdropper uses the fact that a candidate p need not ever be more than 50 bits, the problem is still difficult. For in this case, 2 50 divisions would take about 2 30 seconds, or about 34 years. Since each division takes time O(n) and there are 2 4n total divisions, the asymptotic running time is O(n 2 4n ). 9

11 Solution C-4.8 One possible solution is f(n) = n 2 +(1+sin(n)). Solution C-4.9 n i=1 Z n+1 i 2 < x 2 dx < (n+1)3 = O(n 3 ) 0 3 Solution C-4.11 log b f(n) = log f(n)/logb, but 1/logb is a constant. Solution C-4.12 Pair up all the items and compare them, producing a set of candidate minima and candidate maxima. Now with n/2 1 comparisons we can find the minimum of the minima and the maximum of the maxima. The total number of comparisons is 3n/2 2. Solution C-4.13 The number is one more than the total number of visits each friend can make while still being able to make one more allowed visit, that is, the sum where each friend i visits i 1 times. In other words, the the minimum value for C such that Bob should know that one of his friends has visited his/her maximum allowed number of times is n(n 1)/2+1. Solution C-4.14 The induction assumes that the set of n 1 sheep without a and the set of n 1 sheep without b have a sheep in common. Clearly this is not true for n = 2 sheep. If a base case of 2 sheep could be shown, then the induction would be valid. Algorithm FindPair(A, i, j, k): Input: An integer subarray A[i.. j] and integer k Output: Returns true if there are two elements of A[i.. j] that sum to k if i = j then return false else if A[i]+A[ j] < k then return FindPair(A,i+1, j,k) else if A[i]+A[ j] > k then return FindPair(A,i, j 1,k) else return true 10

12 Solution C-4.20 First calculate the sum n 1 2. Then calculate the sum of all values in the array A. The missing element is the difference between these two numbers. Solution C-4.22 i=1 = n(n 1) For convenience assume that n is even. Then n i=1 log 2 i log 2 n = nlog 2 n. i=1 Solution C-4.23 Number each bottle from 1 to n. Select logn tasters and map each taster to a bit. On the first day of the month, a taster samples a wine if, in the binary representation of the wine s number, his bit is 1. For example, if taster A is assigned to the lowest order bit and there are 5 bottles, he will sample bottles 1, 3, and 5. If taster B is assigned to the highest order bit, he will sample bottles 4 and 5. After the month is over, the number of the poisoned bottle can be determined. If a taster dies, then the bit they mapped to is a 1 in the poisoned bottle s number. Otherwise, the bit is a 0. Solution C-4.26 The idea is to keep a running sum of the column index of each row. Start at the bottom left of the matrix. Walk across the row until a 0 is found. When the first 0 is found, add the column index to the running sum then step up to the next row (without resetting the column position). Continue this procedure until the top row is traversed. 11

13 Chapter 5 Reinforcement Solution R-5.3 The size of the stack is = 18. Solution R Solution R-5.5 3, 8, 2, 1, 6, 7, 4, 9 Solution R-5.6 If the stack is empty, then return (the stack is empty). Otherwise, pop the top element from the stack and recur. Solution R-5.7 An arithmetic expression has matching grouping symbols if it has one of the following structures, where S denotes an arithmetic expression without grouping symbols, and E, E, and E recursively denote an arithmetic expression with matching grouping symbols: S E (E)E E [E]E E {EE Solution R-5.8 5, 3, 2, 8, 9, 1, 7, 6 Solution R-5.9 The size of the queue is = 22. Solution R-5.10 f = 10 and r = 2. Solution R , 9, 3, 3, 7, 7 12

14 Solution R-5.12 D.addLast(D.removeFirst()) D.addLast(D.removeFirst()) D.addLast(D.removeFirst()) Q.enqueue(D.removeFirst()) Q.enqueue(D.removeFirst()) D.addFirst(Q.dequeue()) D.addFirst(Q.dequeue()) D.addFirst(D.removeLast()) D.addFirst(D.removeLast()) D.addFirst(D.removeLast()) Creativity Solution C-5.2 The solution is to actually use the queue Q to process the elements in two phases. In the first phase, we iteratively pop each the element from S and enqueue it in Q, and then we iteratively dequeue each element from Q and push it into S. This reverses the elements in S. Then we repeat this same process, but this time we also look for the element x. By passing the elements through Q and back to S a second time, we reverse the reversal, thereby putting the elements back into S in their original order. Solution C-5.4 x S.pop() if x < S. () then x S.pop() Note that if the largest integer is the first or second element of S, then x will store it. Thus, x stores the largest element with probability 2/3. Solution C-5.5 To implement the stack ADT using two queues, Q1 and Q2, we can simply enqueue elements into Q1 whenever a push call is made. This takes O(1) time to complete. For pop calls, we can dequeue all elements of Q1 and enqueue them into Q2 except for the last element which we set aside in a temp variable. We then return the elements to Q1 by dequeuing from Q2 and enqueuing into Q1. The last element that we set aside earlier is then returned as the result of the pop. Thus, performing a pop takes O(n) time. Solution C-5.6 Let S be an array-based stack with capacity n. We will store integer triples (i, j,k) in the stack S, where each such triple stands for the fact that A[i, j] = k, for a cell A[i, j] that we wish to actually use. But instead of storing k in this cell, we instead store the index, m, of where the triple (i, j,k) is stored in the stack S. To read a cell, A[i, j], then, we set m = A[i, j] (which might be garbage), and, if 0 m top, then we go to S[m] and read the triple (i, j,k) that is there. If i = i and j = j, then we know that this A[i, j] was previously assigned a value and that value is k. Otherwise, the real value of A[i, j] is 0. To write the value k to a cell A[i, j] we push (i, j,k) on S and set A[i, j] = top. 13

15 Solution C-5.11 Alice should put on even integer in S and all the other 99 integers in T. This gives her a 74/99 (roughly 74.7%) chance of winning. Solution C-5.12 Mazie and Daisy go across (4 min.), Daisy comes back (4 min.), Crazy and Lazy go across (20 min.), Mazie comes back (2 min.), and then Mazie and Daisy go across (4 min.). 14

16 Chapter 6 Reinforcement Solution R-6.5 The methods size() and isempty() run in constant time because of the instance variable n. This variable can easily be returned or compared to give the results for these two methods. The method elematrank(i) is also constant because of the underlying array implementation of the array list. Since we are using an array, an access at a particular index is done with a simple A[i] reference. The replace(i, e) method can also be done with a quick access to an index and a change of element, thus, it is also constant. However, the methods add and remove take linear time due to the nature of an array. When inserting at certain index, we must first move over (increase the index of) every element that will follow (has a higher index than) this element. This can take up to n moves for an array of size n. Likewise, for a removal, all of the elements that followed the removed element in the array list previous to the removal now need to be shifted down (lowered in index). Again, this can take up to n moves. Solution R-6.7 Let us assume that one cyber-dollar is enough to pay for the execution of each push operation in S, excluding the time spent for growing the array. Now, however, growing the array from size k to size 2k requires 3k cyber-dollars. Once again, we will need to account for this cost with our bank account in the elements of the last half of the array list. To grow from 2 i to 2 i+1, we need 3 2 i cyber dollars. Thus, from the second half of the array list the last 2 i 1 elements we need to have 6 cyber-dollars apiece stored away. So, overall, we need to charge 7 cyber-dollars for each push operation: 6 for future growth and 1 for insertion. Solution R-6.8 Solution R-6.14 The minimum is 0, since we could have accessed each element exactly k times. the maximum is n 1, since we could have accessed just one element kn times. Solution R-6.16 If the sequence has one element, then check if this element is k, and return the appropriate answer. Otherwise, remove the first element of the sequence. If it is k, return that we have found the element. Otherwise, recurse on the remaining sequence. Solution R-6.17 Solution R-6.20 The total running time for adding n elements in this way is O(n 2 ). 15

17 Algorithm addbefore(p,e): Create a new node v v.setelement(e) v.setprev(p.getprev()) {link v to its predecessor v.setnext(p) {link v to its successor (p.getprev()).setnext(v) {link p s old predecessor to v p.setprev(v) {link p to its new predecessor, v numelts++ return v {the position for the element e Algorithm addfirst(e): Create a new node v v.setelement(e) header.getnext().setprev(v) v.setnext(header.getnext()) header.setnext()v numelts++ return v Algorithm addlast(e): Create a new node v v.setelement(e) trailer.getprev().setnext(v) v.setprev(trailer.getprev()) trailer.setprev(v) numelts++ return v Algorithm makefirst(p): (p.getprev()).setnext(p.getnext()) (p.getnext()).setprev(p.getprev()) p..setprev(header) p.setnext(header.getnext()) header.setnext(p) Solution R-6.21 For addlast(e): if isempty() then return addfirst(e); else return addafter(last(),e); For addbefore(p,e): checkposition(p); if p == first() then return addfirst(e); else return addafter(prev(p),e); (We don t actually need to use the next(p) method.) 16

18 Creativity Solution C-6.1 public class ShrinkingArrayList extends ArrayIndexList { public void shrinktofit( ) { Object[] newbuffer = new Object[size]; for( int i = 0; i < size; i++ ) { newbuffer[i] = a[i]; a = newbuffer; Solution C-6.5 // presuming that r is within range public void add( int r, Object e ) { if( size == capacity ) { capacity = capacity*2; Object[ ] b = new Object[capacity]; for( int i=0; i<r; i++ ) { b[i] = a[i]; b[r] = e; for( int i=r+1; i < size+1; i++ ) { b[i] = a[i 1]; a=b; size++; Solution C-6.9 Deque Method Realization with Array List Methods size() size() isempty() isempty() getfirst() get(size() 1) getlast() get(0) addfirst(e) add(size(), e) addlast(e) add(0, e) removefirst() remove(size() 1) removelast() remove(0) 17

19 Solution C-6.10 Maintain a capacity variable and a elementcount variable. Also maintain the variables indexfirst andindexlast. Presuming that overflow doesn t occur, insertion at index 0 involves inserting the element in array position indexfirst 1 if indexfirst is greater than 0. Otherwise it is inserted at capacity 1. Then indexfirst is updated to reflect the array index the new element was inserted into. Removal from index 0 involves incrementingindexfirst mod capacity. The array index of elematrank(x) can be calculated by x+indexfristmodcapacity Solution C-6.11 For each i from 0 to n 1, swap the element at index i with a randomly-chosen element from the array list. Solution C-6.18 The solution to this exercise is actually posted as a supplement in the instructors area. Solution C-6.19 The solution to this exercise is actually posted as a supplement in the instructors area. Solution C-6.22 Use a Boolean array of size at most 4n, where index i is true if and only if i is in the sequence. Initially, all cells are false, then process the sequence setting cell i to true for each integer i in L. At the end, scan the array for a false cell. The corresponding index is not in the list. Note that such a cell must exist, since there are at least 2n k-bit positive integers. It takes O(n) time to compute this value. Solution C-6.23 Any algorithm that misses even one integer in L and reports that some integer i is not in L is overlooking the possibility that the missed value in L is i. Solution C-6.24 Find the integer in L with maximum absolute value. Add one to twice the absolute value of this integer. Solution C-6.25 The running time is O(n), as it is O(n+n/2+n/4+n/8+ ). 18

20 Chapter 7 Reinforcement Solution R-7.8 The running time is O(n v ), where n v is the number of nodes in the subtree rooted at node v. Solution R-7.11 The tree expresses the formula (6/(1 (5/7))). Solution R-7.12 It is not possible for the postorder and preorder traversal of a tree with more than one node to visit the nodes in the same order. A preorder traversal will always visit the root node first, while a postorder traversal node will always visit an external node first. It is possible for a preorder and a postorder traversal to visit the nodes in the reverse order. Consider the case of a tree with only two nodes. Solution R-7.13 It is not possible for the post and pre order traversals to visit the nodes of a proper binary tree in the same order for the same reason in the previous question. It is not possible for the post and pre order traversals to visit the nodes of a proper binary tree in the reverse order. Let a be the root of a proper binary tree and let T 1 and T 2 be the left and right subtrees. A postorder traversal would visit the postorder traversal of T 1, the postorder traversal of T 2 and then node a while the preorder traversal would visit node a, the preorder traversal of T 1 and then the preorder traversal of T 2. Clearly the postorder and preorder traversals cannot be the reverse of each other since in both cases, all the nodes of T 1 are visited before all the nodes of T 2. Solution R-7.14 The running is O(n) since parentheticrepresentation is just a preorder traversal with output. Solution R-7.15 E. X A U M F N 19

21 Solution R-7.18 grades hw1 hw2 hw3 homeworks/ pr1 pr2 pr3 projects/ cs016/ buylow sellhigh papers/ market demos/ projects/ grades cs252/ /user/rt/courses Solution R x x ((((3+1)x3)/((9 5)+2)) ((3x(7 4))+6)) Creativity Solution C-7.3 post(v) = desc(v) depth(v) + pre(v). To prove this, consider the difference, post(v) pre(v). This difference is equal to all the nodes counted by postorder but not preorder (the descendents of v, whose number is desc(v)) minus all the nodes counted by preorder but not postorder (the ancestors of v, whose number is depth(v)). Solution C-7.4 We can accomplish the task of printing the string stored at v along with the height of the subtree rooted at v by using a postorder traversal. During this traversal, we will find the height of each node. The height for a node v will be 0 if v is external and one more than the height of the max child for an internal node. Then, we can simply print out the string at v and its height if v is internal. Solution C-7.5 Algorithm preordernext(node v): if visinternal() then return v s left child else Node p = parent of v if v is left child of p then return right child of p else while v is not left child of p do v = p p = p.parent return right child of p T. The worst case running times for these algorithms are all O(n) where n is the height of the tree Solution C-7.6 This can be done using a preorder traversal. When doing a visit in the traversal, simply store the depth of the node s parent incremented by 1. Now, every node will contain its depth. 20

22 Algorithm inordernext(node v): if visinternal() then return v s right child else Node p = parent of v if v is left child of p then return p else while v is not left child of p do v = p p = p.parent return p Algorithm postordernext(node v): if visinternal() then p = parent of v if v = right child of p then return p else v = right child of p while v is not external do v = le ftchildo f v return v else p = parent of v if v is left child of p then return right child of p else return p Solution C-7.7 Algorithm indentedparentheticrepresentation(tree T, Position v, int indent): print out indent number of tabs if T.isExternal(v) then print v.element().tostring() else indent ++ print v.element().tostring() + ( Enumeration children of v = T.children(v) while children of v.hasmoreelements() do Position w = (Position) children of v.nextelement() indentedparentheticrepresentation(t, w, indent) indent print out indent number of tabs 21

23 Solution C-7.8 Let T 1 be a tree of n/2 nodes in a single path from the root to a single external node v. And let T 2 be a tree of n/2 nodes having n/2 +1 external nodes. Now, create T by attaching T 2 to T 1 at v. Solution C-7.9 We will show this using induction. For n I = 0, then n E = 2n I + 1 = 1. This is obviously true. For n I = 1, then n E = 2n I + 1 = 2+1 = 3. Again, this is obviously true from our problem definition. Now let us assume that the n E equation holds true for k < k, i.e., for any n I = k < k, n E = 2n I + 1. Now consider n I = k. Then, n E = 2(k 1)+1+(3 1). That is, the number of external nodes is equal to the number of external nodes for a tree with k 1 internal nodes plus 3 (we added an internal node which must have 3 children) minus 1 (in creating the new internal node, we made an external node into an internal node). Thus, n E = 2k 2+3 = 2k + 1. This is what we needed to show. Solution C-7.11 One way to do this is the following: in the external method, set height and balance to be zero. Then, alter the right method as follows: Algorithm right(): if visinternal(v) then if v.le f tchild.height > v.rightchild.height then v.height = v.le ftchild.height + 1; else v.height = v.rightchild.height + 1; v.balance = absval(v.rightchild.height v.le f tchild.height); printbalancefactor(v) Solution C-7.14 a) yes b) no c) yes, postorder. Solution C-7.23 Solution C-7.26 With an array-based implementation, the binary tree methods positions() and iterator() take O(n) time. This is because we need to step through the entire array and extract each position/element. The replace method takes constant time because of the fact that we can access elements in the array using an index, without having to search the entire array. The root, parent, children, leftchild, rightchild, and sibling methods are also constant because we can find these items with simple calculations (for example, the right child of a node with index n is n+2). Finally, isinternal, isexternal, and isroot 22

24 Algorithm LCA(Node v, Node w): int v d pth v.depth int w d pth w.depth while v d pth > w d pth do v v.parent while w d pth > v d pth do w w.parent while v w do v v.parent w w.parent return v also only take a quick calculation based on indices (whether an index is in the last half of the array, is the first item in the array, etc.). Thus, these methods are also constant. Solution C-7.27 Using a linked structure, the iterator() method is linear because we must still walk through the entire linked representation, getting every element. The root, parent, children, left, right, and sibling methods are all constant because we must follow only one or two links to determine these values. The replace method is also constant time because no traversal of the data structure is needed. We need only to change a few links/pointers in order to complete. The methods isinternal, isexternal, and isroot are also constant since we need only to check local fields or links to determine these. Solution C-7.30 Algorithm eulertour(tree T, Position v): state start while state done do if state = start then if T.isExternal(v) then left action below action right action state = done else left action state on the left v v.le ftchild if state = on the left then if T.isExternal(v) then left action below action right action state = from the left v v.parent else 23

25 left action v v.le ftchild if state = from the left then below action state on the right v v.right if state = on the right then if T.isExternal(v) then state = from the right left action below action right action v v.parent else left action state on the left v v.le ft if state = from the right then right action if T.isRoot(v) then state done else if v is left child of parent then state from the left else state from the right v v.parent Solution C-7.31 Algorithm inorder(tree T): Stack S new Stack() Node v T.root() push v while S is not empty do while v is internal do v v.le ft push v while S is not empty do pop v visit v if v is internal then v v.right push v while v is internal do v v.le ft push v 24

26 Solution C-7.32 Algorithm levelordertraversal(binarytree T): Queue Q = new Queue() Q.enqueue(T.root()) while Q is not empty do Node v Q.dequeue() if T.isInternal(v) then Q.enqueue(v.le f tchild) Q.enqueue(v.rightchild) 25

27 Chapter 8 Reinforcement Solution R-8.4 (1,D), (3,J), (4,B), (5,A), (2,H), (6,L). Solution R-8.5 The best data structure for this air-traffic control simulation is a priority queue. The priority queue will enable the handling of the time-stamps and keep the events in order so that the event with the smallest time-stamp is extracted easily. Solution R Solution R-8.8 Solution R A worst-case sequence for insertion sort would be one that is in descending order of keys, e.g., With this sequence, each element will first be moved to the front and then moved back in the sequence incrementally, as every remaining is processed. Thus, each element 26

28 will be moved n times. For n elements, this means at a total of n 2 times, which implies Ω(n 2 ) time overall. Solution R-8.10 The largest key in a heap may be stored at any external node. Solution R-8.13 Yes, tree T is a heap. It is a complete binary tree and each node stores a key value greater than the key of its parent, except for the root. Solution R-8.14 Since a heap is a complete binary tree, the levels of the heap are filled left to right. Thus, a node with the left child nay not have the right child. However, if a node has the right child, it must also have the left child. Solution R-8.15 With a preorder traversal, a heap that produces its entries in increasing order is that which is represented by the array list [x,1,2,5,3,4,6,7]. There does not exist a heap for which an inorder traversal produces the keys in order. This is because in a heap the parent is always less than all of its children or greater than all of its children. The heap represented by [x,1,5,2,7,6,4,3] is an example of one which produces its keys in decreasing order during a postorder traversal. Solution R-8.17 Consider the last n/2 terms in this sum. Each one is at least logn/2 = logn 1. Thus, this sum is at least (n/2) log n n/2, which is O(n log n). Solution R-8.18 Imagine the heap which is represented by the array list [x,1,5,2,8,9,7,6]. This heap will not produce keys in nondecreasing order when a preorder traversal is used. Solution R-8.19 Imagine the heap which is represented by the array list [x,1,5,2,8,9,7,6]. This heap will not produce keys in nonincreasing order when a postorder traversal is used. Solution R-8.25 Unmonopoly can be played efficiently using two adaptable priority queues (with location-aware entries), one keeping track of the player with minimum amount of money and the other keeping track of the player with the most. Each turn involves pairing up the minimum and maximum elements, redistributing their wealth, and then updating their keys (in both priority queues). These structures allow for constant-time pairing of the minimum and maximum elements and fast logarithmic-time updating of keys. 27

29 Creativity Solution C-8.4 import java.util.comparator; public class integercomparator implements Comparator { private int countbits(object a) { if( a==null ) { throw new RuntimeException("Null Argument"); try{ int numones = 0; int tmp = ((Integer) a).intvalue(); while( tmp!= 0 ) { int bit = tmp & 1; if( bit == 1 ) numones++; tmp = tmp >> 1; return numones; catch( ClassCastException e ) { throw new RuntimeException("Argument is not an Integer"); public int compare(object a, Object b) { int vala = countbits( a ); int valb = countbits( b ); return ( vala valb ); Solution C-8.5 Maintain a variable m initialized to 0. On a push operation for element e, call insert(m,e) and decrement m. On a pop operation, call remove and increment m. Solution C-8.6 Maintain a maxkey variable initialized to 0. On an enqueue operation for element e, call insertitem(maxkey, e) and incrementmaxkey. On a dequeue operation, call removeminelement and decrementmaxkey. 28

30 Solution C-8.13 public Position findinsertionposition() { Position z; // insertion position if( isempty() ) { z = T.root(); else { z = last; while(!t.isroot(z) &&!isleftchild(z) ) { z = T.parent(z); if(!t.isroot(z) ) { z = T.rightChild(T.parent(z)); while(!t.isexternal(z) ) { z = T.leftChild(z); return z; Solution C-8.14 The path to the last node in the heap is given by the path represented by the binary expansion of n with the highest-order bit removed. Solution C-8.15 Starting at the root of the tree, recursively search the left and right subtrees if the root of the subtree has a key value less than k. This algorithm takes O(k) time, because there is no node in T storing a key larger than k that has a descendent storing a key less than k. Solution C-8.17 Build a heap storing the frequent flyers and their mileage, using bottom-up heap construction. This takes O(n) time. Next, call removemin logn times, which takes O(logn logn) time, to determine the top logn flyers. Thus, the total time is O(n). Solution C-8.18 Construct a heap, which takes O(n) time. Then call removemin k times, which takes O(k log n) time. 29

31 Chapter 9 Reinforcement Solution R-9.6 Either polynomial hash codes or cyclic shift hash codes would be good. Solution R-9.17 The worst case time is O(n 2 ). The best case is O(n). Solution R-9.20 The expected running time for maintaining a maxima set if we insert n pairs such that each pair has lower price and performance than one before it is O(nlogn), since each pair is inserted and does not remove any others. Thus, after we perform all these updates, the dictionary holds every pair. If, on the other hand, each pair had a lower price and higher performance than the one before it, then the running time is still O(nlogn), but each new pair also removes the pair that came before it. Thus, after performing all these updates, the dictionary holds just one price-performance pair the best (and last) one. Creativity Solution C-9.3 In order to the find the kth smallest key in the union of the keys from S and T, we can do a double binary search. In other words, we will begin by examining the k/2th element in the array list S. Next, we will find the largest element in T that is less than S[k/2] by binary search. Then, we will add the indices of the elements we were examining in S and T. If the sum equals k, then the max of the two elements is our result. If the sum is greater than k, then we will do a binary search to the right (upwards) in S. If the sum is less than k, then we will do a binary search to the left (downwards) in S. This is followed once again by searching in T for largest element less than the current element in S, etc. This method does a binary search on S which requires O(logn) probes. However, for each probe of the search, it does a binary search on T which takes O(logn) time. Thus, the entire method takes O(log 2 n) time. Solution C-9.5 Simply do a binary search to find an element equal to k. Then step back through the array until you reach the first element equal to k. Finally, step forward through the area adding each element to the iterator until you reach the first element that is not equal to k. This takes O(logn) time for the search and then at most s time to search back to the beginning of the run of k s and s time return all of the elements with key k. Therefore we have a solution running in at most O(logn+s) time. Solution C-9.8 When we remove an entry from a hash table that uses linear probing without using deleted element markers, we need to rearrange the hash table contents so that it seems the removed entry never existed. This action can be done by simple incrementally stepping forward through the table (much 30

32 as we do when there are collisions) and moving back one spot each key k for which f(k) equals f(keyo f removedentry). We continue walking through the table until we encounter the first entry for which the f(k) value differs. Solution C-9.9 Sort the pairs by cost. Then scan this list looking at the performance values. Remove any that have performance values worse than the (unremoved) pair that came before. Solution C-9.14 To count the number of 1 s in A, we can do a binary search on each row of A to determine the position of the last 1 in that row. Then we can simply sum up these values to obtain the total number of 1 s in A. This takes O(logn) time to find the last 1 in each row. Done for each of the n rows, then this takes O(n log n) time. Solution C-9.15 Use a skip list map to implement something similar to the HashTableMultiMap class given in the book. There will only be r nodes in the bottom level of the skip list, and each of these will point to a linked list of elements with the same key. Thus, all the query and update operations will run in O(logr) expected time, and the getall method will run in O(logr+ s) expected time. Solution C-9.16 The solution is actually quite simple just use something like the HashTableMultiMap class given in the book, but make sure that the capacity of the underlying hash table is always O(n). Another possibility is to use a linked hash table, which keeps its entries in a linked list in addition to the hash table. Either way we would get that the entryset() method would in O(n) time. Solution C-9.17 The bag ADT can be implemented using a stack. An add with the stack is simply a push operation (constant time) and a remove is simply a pop (also constant time). 31

33 Chapter 10 Reinforcement Solution R-10.2 A subtree of equal keys must be a single chain of right children. Solution R Solution R (2 w/ 1 as root, 1 w/ 2 as root, 2 w/ 3 as root). 32

34 Solution R-10.6 There are several solutions. One is to draw the binary search tree created by the input sequence: 9,5,12,7,13. Now draw the tree created when you switch the 5 and the 7 in the input sequence: 9,7,12,5,13. Solution R-10.7 There are several solutions. One is to draw the AVL tree created by the input sequence: 9,5,12,7,13. Now draw the tree created when you switch the 5 and the 7 in the input sequence: 9,7,12,5,13. Solution R-10.8 The rotation in Figure 9.9 is a double rotation. The rotation in Figure 9.11 is a single rotation. Solution R Solution R Solution R No. One property of a (2,4) tree is that all external nodes are at the same depth. The multi-way search tree of the example does not adhere to this property. 33

35 Solution R The key k 2 would be stored at v s parent in this case. This is done in order to maintain the ordering of the keys within the tree. By storing k 2 at v s parent, all of the children would still be ordered such that the children to the left of the key are less than the key and those to the right of the key are greater than the key. Solution R insertion order: 4, 6, 12, 15, 3, insertion order: 12, 3, 6, 4, 5, Solution R The worst-case height of an AVL tree or red-black tree with 100,000 entries is 2log100,000. A (2,4) tree storing these same number of entries would have a worst-case height of log100,000. A binary search tree storing such a set would have a worst-case height of 100,000. Solution R Yes, splay trees can sort in O(nlogn) time in the worst case: just insert all the elements and then do an inorder traversal of the splay tree. This runs in worst case O(nlogn) time because each individual insert operation runs in O(logn) amortized time and there are n insertions. Creativity Solution C-10.2 Note that after finding k, if it occurs again, it will be in the left most internal node of the right subtree. 34

36 Solution C-10.4 Algorithm findallelements(k, v, c): Input: The search key k, a node of the binary search tree v and a collection c Output: An iterable collection containing the found entries if v is an external node then return c if k = key(v) then c.addlast(v) return findallelements(k, T.right(v), c) else if k < key(v) then return findallelements(k, T.left(v), c) else {we know k > key(v) return findallelements(k,t.right(v),c) 35

37 Solution C-10.9 Search for k 1 and then k 2, each while marking the path down to that node. Observe that all the nodes between the path towards k 1 and k 2 are within the specified range. A modified inorder traversal can be performed, using the given paths as boundaries and starting at the intersection of the two paths, to enumerate all the entries inclusively between k 1 and k 2. Solution C For each node of the tree, maintain the size of the corresponding subtree, defined as the number of internal nodes in that subtree. While performing the search operation in both the insertion and deletion, the subtree sizes can be either incremented or decremented. During the rebalancing, care must be taken to update the subtree sizes of the three nodes involved (labeled a, b, and c by the restructure algorithm). To calculate the number of nodes in a range (k 1,k 2 ), search for both k 1 and k 2, and let P 1 and P 2 be the associated search paths. Call v the last node common to the two paths. Traverse path P 1 from v to k 1. For each internal node w v encountered, if the right child of w is in not in P 1, add one plus the size of the subtree of the child to the current sum. Similarly, traverse path P 2 from v to k 2. For each internal node w v encountered, if the left child of w is in not in P 2, add one plus the size of the subtree of the left to the current sum. Finally, add one to the current sum (for the key stored at node v). Solution C Assume that T and U have heights h t and h u and h t > h u. Remove the smallest entry from U. Insert this entry into the rightmost node of tree T at height h t h u 1. Link this node to the root of tree U. The remove operation on U takes O(logm) time and the insert operation on T takes O(logn) time. Solution C Since the nodes store keys in order, when keys are distinct, we can detect when the children s subtrees are swapped. This indication can be used to mark nodes as red. Detecting this indication increases the search and update times by a constant factor, but the asymptotic running times remain the same. Solution C All nodes should initially be black. If a node is black and it s left and right sub trees have different heights, the node should be colored red (excluding the root). Solution C Store the elements in an AVL or red-black tree, so that their inorder is the same as in the array list. For each node v in this tree, store a count c(v) of the number of nodes in the subtree rooted at v. This count can be used to perform searches for the element at index i. This count is also easy to maintain during trinode restructures and node insertions and removals. 36

38 Chapter 11 Reinforcement Solution R-11.2 Merge-sort takes O(nlogn) time, as it is oblivious to the case when there are only two possible values. On the other hand, the way we have defined quick-sort with a three-way split implies that using quick-sort to sort S will take only O(n) time. Solution R-11.3 O(n) time. Solution R-11.4 For each element in a sequence of size n there is exactly one exterior node in the merge-sort tree associated with it. Since the merge-sort tree is binary with exactly n exterior nodes, we know it has height logn. Solution R-11.5 The downward arrows represent a recursive call of merge sort. The upward arrows represent the return of a recursive call. Solution R-11.8 Merge sequences A and B into a new sequence C (i.e., call merge(a,b,c)). Do a linear scan through the sequence C removing all duplicate elements (i.e., if the next element is equal to the current element, remove it). Solution R O(nlogn) time. Solution R The sequence should have the property that the selected pivot is the largest element in the subsequence. This is to say that if G contains no elements, the worst case Ω(n 2 ) bound is obtained. Solution R The pseudo-code is exactly the same as in the book, except we add one additional step (as the second line): Swap the elements at S[b] and S[i], where i is a random integer in [a,b]. Solution R In order for x to belong to more than i subproblems in size group i, x has to belong to i subproblems with bad calls. This event occurs with probability 1/2 2logn = 1/n 2 for i = 2logn. 37

Solutions Manual. Data Structures and Algorithms in Java, 5th edition International Student Version. M. T. Goodrich and R.

Solutions Manual. Data Structures and Algorithms in Java, 5th edition International Student Version. M. T. Goodrich and R. Solutions Manual Data Structures and Algorithms in Java, 5th edition International Student Version M. T. Goodrich and R. Tamassia Chapter 1 Reinforcement Solution R-1.1 Since, after the clone, A[4] and

More information

INFO1x05 Tutorial 6. Exercise 1: Heaps and Priority Queues

INFO1x05 Tutorial 6. Exercise 1: Heaps and Priority Queues INFO1x05 Tutorial 6 Heaps and Priority Queues Exercise 1: 1. How long would it take to remove the log n smallest elements from a heap that contains n entries, using the operation? 2. Suppose you label

More information

CS301 - Data Structures Glossary By

CS301 - Data Structures Glossary By CS301 - Data Structures Glossary By Abstract Data Type : A set of data values and associated operations that are precisely specified independent of any particular implementation. Also known as ADT Algorithm

More information

Data Structures Question Bank Multiple Choice

Data Structures Question Bank Multiple Choice Section 1. Fundamentals: Complexity, Algorthm Analysis 1. An algorithm solves A single problem or function Multiple problems or functions Has a single programming language implementation 2. A solution

More information

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

COSC 2007 Data Structures II Final Exam. Part 1: multiple choice (1 mark each, total 30 marks, circle the correct answer) COSC 2007 Data Structures II Final Exam Thursday, April 13 th, 2006 This is a closed book and closed notes exam. There are total 3 parts. Please answer the questions in the provided space and use back

More information

Chapter 2: Basic Data Structures

Chapter 2: Basic Data Structures Chapter 2: Basic Data Structures Basic Data Structures Stacks Queues Vectors, Linked Lists Trees (Including Balanced Trees) Priority Queues and Heaps Dictionaries and Hash Tables Spring 2014 CS 315 2 Two

More information

COMP Data Structures

COMP Data Structures COMP 2140 - Data Structures Shahin Kamali Topic 5 - Sorting University of Manitoba Based on notes by S. Durocher. COMP 2140 - Data Structures 1 / 55 Overview Review: Insertion Sort Merge Sort Quicksort

More information

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

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 FINALTERM EXAMINATION Fall 2009 CS301- Data Structures Question No: 1 The data of the problem is of 2GB and the hard disk is of 1GB capacity, to solve this problem we should Use better data structures

More information

21# 33# 90# 91# 34# # 39# # # 31# 98# 0# 1# 2# 3# 4# 5# 6# 7# 8# 9# 10# #

21# 33# 90# 91# 34# # 39# # # 31# 98# 0# 1# 2# 3# 4# 5# 6# 7# 8# 9# 10# # 1. Prove that n log n n is Ω(n). York University EECS 11Z Winter 1 Problem Set 3 Instructor: James Elder Solutions log n n. Thus n log n n n n n log n n Ω(n).. Show that n is Ω (n log n). We seek a c >,

More information

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

MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct. MID TERM MEGA FILE SOLVED BY VU HELPER Which one of the following statement is NOT correct. In linked list the elements are necessarily to be contiguous In linked list the elements may locate at far positions

More information

Data Structure. A way to store and organize data in order to support efficient insertions, queries, searches, updates, and deletions.

Data Structure. A way to store and organize data in order to support efficient insertions, queries, searches, updates, and deletions. DATA STRUCTURES COMP 321 McGill University These slides are mainly compiled from the following resources. - Professor Jaehyun Park slides CS 97SI - Top-coder tutorials. - Programming Challenges book. Data

More information

Summer Final Exam Review Session August 5, 2009

Summer Final Exam Review Session August 5, 2009 15-111 Summer 2 2009 Final Exam Review Session August 5, 2009 Exam Notes The exam is from 10:30 to 1:30 PM in Wean Hall 5419A. The exam will be primarily conceptual. The major emphasis is on understanding

More information

CSE Data Structures and Introduction to Algorithms... In Java! Instructor: Fei Wang. Mid-Term Exam. CSE2100 DS & Algorithms 1

CSE Data Structures and Introduction to Algorithms... In Java! Instructor: Fei Wang. Mid-Term Exam. CSE2100 DS & Algorithms 1 CSE 2100 Data Structures and Introduction to Algorithms...! In Java!! Instructor: Fei Wang! Mid-Term Exam CSE2100 DS & Algorithms 1 1. True or False (20%=2%x10)! (1) O(n) is O(n^2) (2) The height h of

More information

Module 2: Classical Algorithm Design Techniques

Module 2: Classical Algorithm Design Techniques Module 2: Classical Algorithm Design Techniques Dr. Natarajan Meghanathan Associate Professor of Computer Science Jackson State University Jackson, MS 39217 E-mail: natarajan.meghanathan@jsums.edu Module

More information

CS-301 Data Structure. Tariq Hanif

CS-301 Data Structure. Tariq Hanif 1. The tree data structure is a Linear data structure Non-linear data structure Graphical data structure Data structure like queue FINALTERM EXAMINATION Spring 2012 CS301- Data Structure 25-07-2012 2.

More information

O(n): printing a list of n items to the screen, looking at each item once.

O(n): printing a list of n items to the screen, looking at each item once. UNIT IV Sorting: O notation efficiency of sorting bubble sort quick sort selection sort heap sort insertion sort shell sort merge sort radix sort. O NOTATION BIG OH (O) NOTATION Big oh : the function f(n)=o(g(n))

More information

CS102 Binary Search Trees

CS102 Binary Search Trees CS102 Binary Search Trees Prof Tejada 1 To speed up insertion, removal and search, modify the idea of a Binary Tree to create a Binary Search Tree (BST) Binary Search Trees Binary Search Trees have one

More information

Lecture 6: Analysis of Algorithms (CS )

Lecture 6: Analysis of Algorithms (CS ) Lecture 6: Analysis of Algorithms (CS583-002) Amarda Shehu October 08, 2014 1 Outline of Today s Class 2 Traversals Querying Insertion and Deletion Sorting with BSTs 3 Red-black Trees Height of a Red-black

More information

Course Review. Cpt S 223 Fall 2009

Course Review. Cpt S 223 Fall 2009 Course Review Cpt S 223 Fall 2009 1 Final Exam When: Tuesday (12/15) 8-10am Where: in class Closed book, closed notes Comprehensive Material for preparation: Lecture slides & class notes Homeworks & program

More information

University of Waterloo Department of Electrical and Computer Engineering ECE250 Algorithms and Data Structures Fall 2014

University of Waterloo Department of Electrical and Computer Engineering ECE250 Algorithms and Data Structures Fall 2014 University of Waterloo Department of Electrical and Computer Engineering ECE250 Algorithms and Data Structures Fall 2014 Midterm Examination Instructor: Ladan Tahvildari, PhD, PEng, SMIEEE Date: Tuesday,

More information

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

Quiz 1 Solutions. (a) f(n) = n g(n) = log n Circle all that apply: f = O(g) f = Θ(g) f = Ω(g) Introduction to Algorithms March 11, 2009 Massachusetts Institute of Technology 6.006 Spring 2009 Professors Sivan Toledo and Alan Edelman Quiz 1 Solutions Problem 1. Quiz 1 Solutions Asymptotic orders

More information

INSTITUTE OF AERONAUTICAL ENGINEERING

INSTITUTE OF AERONAUTICAL ENGINEERING INSTITUTE OF AERONAUTICAL ENGINEERING (Autonomous) Dundigal, Hyderabad - 500 043 COMPUTER SCIENCE AND ENGINEERING TUTORIAL QUESTION BANK Course Name Course Code Class Branch DATA STRUCTURES ACS002 B. Tech

More information

DATA STRUCTURE : A MCQ QUESTION SET Code : RBMCQ0305

DATA STRUCTURE : A MCQ QUESTION SET Code : RBMCQ0305 Q.1 If h is any hashing function and is used to hash n keys in to a table of size m, where n

More information

UNIT III BALANCED SEARCH TREES AND INDEXING

UNIT III BALANCED SEARCH TREES AND INDEXING UNIT III BALANCED SEARCH TREES AND INDEXING OBJECTIVE The implementation of hash tables is frequently called hashing. Hashing is a technique used for performing insertions, deletions and finds in constant

More information

CS8391-DATA STRUCTURES QUESTION BANK UNIT I

CS8391-DATA STRUCTURES QUESTION BANK UNIT I CS8391-DATA STRUCTURES QUESTION BANK UNIT I 2MARKS 1.Define data structure. The data structure can be defined as the collection of elements and all the possible operations which are required for those

More information

Describe how to implement deque ADT using two stacks as the only instance variables. What are the running times of the methods

Describe how to implement deque ADT using two stacks as the only instance variables. What are the running times of the methods Describe how to implement deque ADT using two stacks as the only instance variables. What are the running times of the methods 1 2 Given : Stack A, Stack B 3 // based on requirement b will be reverse of

More information

Assume you are given a Simple Linked List (i.e. not a doubly linked list) containing an even number of elements. For example L = [A B C D E F].

Assume you are given a Simple Linked List (i.e. not a doubly linked list) containing an even number of elements. For example L = [A B C D E F]. Question Assume you are given a Simple Linked List (i.e. not a doubly linked list) containing an even number of elements. For example L = [A B C D E F]. a) Draw the linked node structure of L, including

More information

Course Review for Finals. Cpt S 223 Fall 2008

Course Review for Finals. Cpt S 223 Fall 2008 Course Review for Finals Cpt S 223 Fall 2008 1 Course Overview Introduction to advanced data structures Algorithmic asymptotic analysis Programming data structures Program design based on performance i.e.,

More information

DDS Dynamic Search Trees

DDS Dynamic Search Trees DDS Dynamic Search Trees 1 Data structures l A data structure models some abstract object. It implements a number of operations on this object, which usually can be classified into l creation and deletion

More information

9/29/2016. Chapter 4 Trees. Introduction. Terminology. Terminology. Terminology. Terminology

9/29/2016. Chapter 4 Trees. Introduction. Terminology. Terminology. Terminology. Terminology Introduction Chapter 4 Trees for large input, even linear access time may be prohibitive we need data structures that exhibit average running times closer to O(log N) binary search tree 2 Terminology recursive

More information

1. [1 pt] What is the solution to the recurrence T(n) = 2T(n-1) + 1, T(1) = 1

1. [1 pt] What is the solution to the recurrence T(n) = 2T(n-1) + 1, T(1) = 1 Asymptotics, Recurrence and Basic Algorithms 1. [1 pt] What is the solution to the recurrence T(n) = 2T(n-1) + 1, T(1) = 1 2. O(n) 2. [1 pt] What is the solution to the recurrence T(n) = T(n/2) + n, T(1)

More information

CMSC351 - Fall 2014, Homework #2

CMSC351 - Fall 2014, Homework #2 CMSC351 - Fall 2014, Homework #2 Due: October 8th at the start of class Name: Section: Grades depend on neatness and clarity. Write your answers with enough detail about your approach and concepts used,

More information

Ch04 Balanced Search Trees

Ch04 Balanced Search Trees Presentation for use with the textbook Algorithm Design and Applications, by M. T. Goodrich and R. Tamassia, Wiley, 05 Ch0 Balanced Search Trees v 3 8 z Why care about advanced implementations? Same entries,

More information

Basic Data Structures (Version 7) Name:

Basic Data Structures (Version 7) Name: Prerequisite Concepts for Analysis of Algorithms Basic Data Structures (Version 7) Name: Email: Concept: mathematics notation 1. log 2 n is: Code: 21481 (A) o(log 10 n) (B) ω(log 10 n) (C) Θ(log 10 n)

More information

Trees, Part 1: Unbalanced Trees

Trees, Part 1: Unbalanced Trees Trees, Part 1: Unbalanced Trees The first part of this chapter takes a look at trees in general and unbalanced binary trees. The second part looks at various schemes to balance trees and/or make them more

More information

The questions will be short answer, similar to the problems you have done on the homework

The questions will be short answer, similar to the problems you have done on the homework Introduction The following highlights are provided to give you an indication of the topics that you should be knowledgeable about for the midterm. This sheet is not a substitute for the homework and the

More information

MLR Institute of Technology

MLR Institute of Technology MLR Institute of Technology Laxma Reddy Avenue, Dundigal, Quthbullapur (M), Hyderabad 500 043 Phone Nos: 08418 204066 / 204088, Fax : 08418 204088 TUTORIAL QUESTION BANK Course Name : DATA STRUCTURES Course

More information

Stores a collection of elements each with an associated key value

Stores a collection of elements each with an associated key value CH9. PRIORITY QUEUES ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN JAVA, GOODRICH, TAMASSIA AND GOLDWASSER (WILEY 201) PRIORITY QUEUES Stores a collection

More information

CH 8. HEAPS AND PRIORITY QUEUES

CH 8. HEAPS AND PRIORITY QUEUES CH 8. HEAPS AND PRIORITY QUEUES ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN C++, GOODRICH, TAMASSIA AND MOUNT (WILEY 2004) AND SLIDES FROM NANCY

More information

Balanced Binary Search Trees. Victor Gao

Balanced Binary Search Trees. Victor Gao Balanced Binary Search Trees Victor Gao OUTLINE Binary Heap Revisited BST Revisited Balanced Binary Search Trees Rotation Treap Splay Tree BINARY HEAP: REVIEW A binary heap is a complete binary tree such

More information

CS2223: Algorithms Sorting Algorithms, Heap Sort, Linear-time sort, Median and Order Statistics

CS2223: Algorithms Sorting Algorithms, Heap Sort, Linear-time sort, Median and Order Statistics CS2223: Algorithms Sorting Algorithms, Heap Sort, Linear-time sort, Median and Order Statistics 1 Sorting 1.1 Problem Statement You are given a sequence of n numbers < a 1, a 2,..., a n >. You need to

More information

CH. 8 PRIORITY QUEUES AND HEAPS

CH. 8 PRIORITY QUEUES AND HEAPS CH. 8 PRIORITY QUEUES AND HEAPS ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN C++, GOODRICH, TAMASSIA AND MOUNT (WILEY 2004) AND SLIDES FROM NANCY

More information

COMP 250 Midterm #2 March 11 th 2013

COMP 250 Midterm #2 March 11 th 2013 NAME: STUDENT ID: COMP 250 Midterm #2 March 11 th 2013 - This exam has 6 pages - This is an open book and open notes exam. No electronic equipment is allowed. 1) Questions with short answers (28 points;

More information

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

Operations on Heap Tree The major operations required to be performed on a heap tree are Insertion, Deletion, and Merging. Priority Queue, Heap and Heap Sort In this time, we will study Priority queue, heap and heap sort. Heap is a data structure, which permits one to insert elements into a set and also to find the largest

More information

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

Lec 17 April 8. Topics: binary Trees expression trees. (Chapter 5 of text) Lec 17 April 8 Topics: binary Trees expression trees Binary Search Trees (Chapter 5 of text) Trees Linear access time of linked lists is prohibitive Heap can t support search in O(log N) time. (takes O(N)

More information

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

CSE 332 Autumn 2013: Midterm Exam (closed book, closed notes, no calculators) Name: Email address: Quiz Section: CSE 332 Autumn 2013: Midterm Exam (closed book, closed notes, no calculators) Instructions: Read the directions for each question carefully before answering. We will

More information

CSCI2100B Data Structures Trees

CSCI2100B Data Structures Trees CSCI2100B Data Structures Trees Irwin King king@cse.cuhk.edu.hk http://www.cse.cuhk.edu.hk/~king Department of Computer Science & Engineering The Chinese University of Hong Kong Introduction General Tree

More information

A set of nodes (or vertices) with a single starting point

A set of nodes (or vertices) with a single starting point Binary Search Trees Understand tree terminology Understand and implement tree traversals Define the binary search tree property Implement binary search trees Implement the TreeSort algorithm 2 A set of

More information

Priority Queues. 1 Introduction. 2 Naïve Implementations. CSci 335 Software Design and Analysis III Chapter 6 Priority Queues. Prof.

Priority Queues. 1 Introduction. 2 Naïve Implementations. CSci 335 Software Design and Analysis III Chapter 6 Priority Queues. Prof. Priority Queues 1 Introduction Many applications require a special type of queuing in which items are pushed onto the queue by order of arrival, but removed from the queue based on some other priority

More information

Computer Science E-22 Practice Final Exam

Computer Science E-22 Practice Final Exam name Computer Science E-22 This exam consists of three parts. Part I has 10 multiple-choice questions that you must complete. Part II consists of 4 multi-part problems, of which you must complete 3, and

More information

1) What is the primary purpose of template functions? 2) Suppose bag is a template class, what is the syntax for declaring a bag b of integers?

1) What is the primary purpose of template functions? 2) Suppose bag is a template class, what is the syntax for declaring a bag b of integers? Review for Final (Chapter 6 13, 15) 6. Template functions & classes 1) What is the primary purpose of template functions? A. To allow a single function to be used with varying types of arguments B. To

More information

Faculty of Science FINAL EXAMINATION COMP-250 A Introduction to Computer Science School of Computer Science, McGill University

Faculty of Science FINAL EXAMINATION COMP-250 A Introduction to Computer Science School of Computer Science, McGill University NAME: STUDENT NUMBER:. Faculty of Science FINAL EXAMINATION COMP-250 A Introduction to Computer Science School of Computer Science, McGill University Examimer: Prof. Mathieu Blanchette December 8 th 2005,

More information

Lecture 7. Transform-and-Conquer

Lecture 7. Transform-and-Conquer Lecture 7 Transform-and-Conquer 6-1 Transform and Conquer This group of techniques solves a problem by a transformation to a simpler/more convenient instance of the same problem (instance simplification)

More information

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

Trees. (Trees) Data Structures and Programming Spring / 28 Trees (Trees) Data Structures and Programming Spring 2018 1 / 28 Trees A tree is a collection of nodes, which can be empty (recursive definition) If not empty, a tree consists of a distinguished node r

More information

Binary Tree. Preview. Binary Tree. Binary Tree. Binary Search Tree 10/2/2017. Binary Tree

Binary Tree. Preview. Binary Tree. Binary Tree. Binary Search Tree 10/2/2017. Binary Tree 0/2/ Preview Binary Tree Tree Binary Tree Property functions In-order walk Pre-order walk Post-order walk Search Tree Insert an element to the Tree Delete an element form the Tree A binary tree is a tree

More information

D. Θ nlogn ( ) D. Ο. ). Which of the following is not necessarily true? . Which of the following cannot be shown as an improvement? D.

D. Θ nlogn ( ) D. Ο. ). Which of the following is not necessarily true? . Which of the following cannot be shown as an improvement? D. CSE 0 Name Test Fall 00 Last Digits of Mav ID # Multiple Choice. Write your answer to the LEFT of each problem. points each. The time to convert an array, with priorities stored at subscripts through n,

More information

Instructions. Definitions. Name: CMSC 341 Fall Question Points I. /12 II. /30 III. /10 IV. /12 V. /12 VI. /12 VII.

Instructions. Definitions. Name: CMSC 341 Fall Question Points I. /12 II. /30 III. /10 IV. /12 V. /12 VI. /12 VII. CMSC 341 Fall 2013 Data Structures Final Exam B Name: Question Points I. /12 II. /30 III. /10 IV. /12 V. /12 VI. /12 VII. /12 TOTAL: /100 Instructions 1. This is a closed-book, closed-notes exam. 2. You

More information

Elementary Data Structures. Stacks, Queues, & Lists Amortized analysis Trees

Elementary Data Structures. Stacks, Queues, & Lists Amortized analysis Trees Elementary Data Structures Stacks, Queues, & Lists Amortized analysis Trees The Stack ADT ( 2.1.1) The Stack ADT stores arbitrary objects Insertions and deletions follow the last-in first-out scheme Think

More information

A6-R3: DATA STRUCTURE THROUGH C LANGUAGE

A6-R3: DATA STRUCTURE THROUGH C LANGUAGE A6-R3: DATA STRUCTURE THROUGH C LANGUAGE NOTE: 1. There are TWO PARTS in this Module/Paper. PART ONE contains FOUR questions and PART TWO contains FIVE questions. 2. PART ONE is to be answered in the TEAR-OFF

More information

UNIVERSITY OF WATERLOO DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING E&CE 250 ALGORITHMS AND DATA STRUCTURES

UNIVERSITY OF WATERLOO DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING E&CE 250 ALGORITHMS AND DATA STRUCTURES UNIVERSITY OF WATERLOO DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING E&CE 250 ALGORITHMS AND DATA STRUCTURES Midterm Examination Douglas Wilhelm Harder 1.5 hrs, 2005/02/17 11 pages Name (last, first):

More information

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

CS251-SE1. Midterm 2. Tuesday 11/1 8:00pm 9:00pm. There are 16 multiple-choice questions and 6 essay questions. CS251-SE1 Midterm 2 Tuesday 11/1 8:00pm 9:00pm There are 16 multiple-choice questions and 6 essay questions. Answer the multiple choice questions on your bubble sheet. Answer the essay questions in the

More information

Red-Black trees are usually described as obeying the following rules :

Red-Black trees are usually described as obeying the following rules : Red-Black Trees As we have seen, the ideal Binary Search Tree has height approximately equal to log n, where n is the number of values stored in the tree. Such a BST guarantees that the maximum time for

More information

COMP : Trees. COMP20012 Trees 219

COMP : Trees. COMP20012 Trees 219 COMP20012 3: Trees COMP20012 Trees 219 Trees Seen lots of examples. Parse Trees Decision Trees Search Trees Family Trees Hierarchical Structures Management Directories COMP20012 Trees 220 Trees have natural

More information

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

Lecture 5. Treaps Find, insert, delete, split, and join in treaps Randomized search trees Randomized search tree time costs Lecture 5 Treaps Find, insert, delete, split, and join in treaps Randomized search trees Randomized search tree time costs Reading: Randomized Search Trees by Aragon & Seidel, Algorithmica 1996, http://sims.berkeley.edu/~aragon/pubs/rst96.pdf;

More information

Lecture: Analysis of Algorithms (CS )

Lecture: Analysis of Algorithms (CS ) Lecture: Analysis of Algorithms (CS583-002) Amarda Shehu Fall 2017 1 Binary Search Trees Traversals, Querying, Insertion, and Deletion Sorting with BSTs 2 Example: Red-black Trees Height of a Red-black

More information

Principles of Algorithm Design

Principles of Algorithm Design Principles of Algorithm Design When you are trying to design an algorithm or a data structure, it s often hard to see how to accomplish the task. The following techniques can often be useful: 1. Experiment

More information

CS8391-DATA STRUCTURES

CS8391-DATA STRUCTURES ST.JOSEPH COLLEGE OF ENGINEERING DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERI NG CS8391-DATA STRUCTURES QUESTION BANK UNIT I 2MARKS 1.Explain the term data structure. The data structure can be defined

More information

CSE373 Fall 2013, Midterm Examination October 18, 2013

CSE373 Fall 2013, Midterm Examination October 18, 2013 CSE373 Fall 2013, Midterm Examination October 18, 2013 Please do not turn the page until the bell rings. Rules: The exam is closed-book, closed-note, closed calculator, closed electronics. Please stop

More information

ECE250: Algorithms and Data Structures Midterm Review

ECE250: Algorithms and Data Structures Midterm Review ECE250: Algorithms and Data Structures Midterm Review Ladan Tahvildari, PEng, SMIEEE Associate Professor Software Technologies Applied Research (STAR) Group Dept. of Elect. & Comp. Eng. University of Waterloo

More information

Heaps Outline and Required Reading: Heaps ( 7.3) COSC 2011, Fall 2003, Section A Instructor: N. Vlajic

Heaps Outline and Required Reading: Heaps ( 7.3) COSC 2011, Fall 2003, Section A Instructor: N. Vlajic 1 Heaps Outline and Required Reading: Heaps (.3) COSC 2011, Fall 2003, Section A Instructor: N. Vlajic Heap ADT 2 Heap binary tree (T) that stores a collection of keys at its internal nodes and satisfies

More information

COS 226 Algorithms and Data Structures Fall Midterm

COS 226 Algorithms and Data Structures Fall Midterm COS 226 Algorithms and Data Structures Fall 2017 Midterm This exam has 10 questions (including question 0) worth a total of 55 points. You have 0 minutes. This exam is preprocessed by a computer, so please

More information

B-Trees and External Memory

B-Trees and External Memory Presentation for use with the textbook, Algorithm Design and Applications, by M. T. Goodrich and R. Tamassia, Wiley, 2015 and External Memory 1 1 (2, 4) Trees: Generalization of BSTs Each internal node

More information

a) For the binary tree shown below, what are the preorder, inorder and post order traversals.

a) For the binary tree shown below, what are the preorder, inorder and post order traversals. CS61CS61B Fall 2014 Guerrilla Section 2 Solutions 1. Trees a) For the binary tree shown below, what are the preorder, inorder and post order traversals. 23 / \ 47 0 / / \ 9 15 100 / \ / \ \ 1 935 12 42

More information

Binary Search Trees Treesort

Binary Search Trees Treesort Treesort CS 311 Data Structures and Algorithms Lecture Slides Friday, November 13, 2009 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks CHAPPELLG@member.ams.org 2005 2009

More information

Search Trees. Undirected graph Directed graph Tree Binary search tree

Search Trees. Undirected graph Directed graph Tree Binary search tree Search Trees Undirected graph Directed graph Tree Binary search tree 1 Binary Search Tree Binary search key property: Let x be a node in a binary search tree. If y is a node in the left subtree of x, then

More information

CS:3330 (22c:31) Algorithms

CS:3330 (22c:31) Algorithms What s an Algorithm? CS:3330 (22c:31) Algorithms Introduction Computer Science is about problem solving using computers. Software is a solution to some problems. Algorithm is a design inside a software.

More information

CS 310 Advanced Data Structures and Algorithms

CS 310 Advanced Data Structures and Algorithms CS 310 Advanced Data Structures and Algorithms Sorting June 13, 2017 Tong Wang UMass Boston CS 310 June 13, 2017 1 / 42 Sorting One of the most fundamental problems in CS Input: a series of elements with

More information

Trees. CSE 373 Data Structures

Trees. CSE 373 Data Structures Trees CSE 373 Data Structures Readings Reading Chapter 7 Trees 2 Why Do We Need Trees? Lists, Stacks, and Queues are linear relationships Information often contains hierarchical relationships File directories

More information

A6-R3: DATA STRUCTURE THROUGH C LANGUAGE

A6-R3: DATA STRUCTURE THROUGH C LANGUAGE A6-R3: DATA STRUCTURE THROUGH C LANGUAGE NOTE: 1. There are TWO PARTS in this Module/Paper. PART ONE contains FOUR questions and PART TWO contains FIVE questions. 2. PART ONE is to be answered in the TEAR-OFF

More information

B-Trees and External Memory

B-Trees and External Memory Presentation for use with the textbook, Algorithm Design and Applications, by M. T. Goodrich and R. Tamassia, Wiley, 2015 B-Trees and External Memory 1 (2, 4) Trees: Generalization of BSTs Each internal

More information

Chapter 5 Data Structures Algorithm Theory WS 2016/17 Fabian Kuhn

Chapter 5 Data Structures Algorithm Theory WS 2016/17 Fabian Kuhn Chapter 5 Data Structures Algorithm Theory WS 06/ Fabian Kuhn Examples Dictionary: Operations: insert(key,value), delete(key), find(key) Implementations: Linked list: all operations take O(n) time (n:

More information

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

CSE 332 Winter 2015: Midterm Exam (closed book, closed notes, no calculators) _ UWNetID: Lecture Section: A CSE 332 Winter 2015: Midterm Exam (closed book, closed notes, no calculators) Instructions: Read the directions for each question carefully before answering. We will give

More information

Lecture 13: AVL Trees and Binary Heaps

Lecture 13: AVL Trees and Binary Heaps Data Structures Brett Bernstein Lecture 13: AVL Trees and Binary Heaps Review Exercises 1. ( ) Interview question: Given an array show how to shue it randomly so that any possible reordering is equally

More information

Bioinformatics Programming. EE, NCKU Tien-Hao Chang (Darby Chang)

Bioinformatics Programming. EE, NCKU Tien-Hao Chang (Darby Chang) Bioinformatics Programming EE, NCKU Tien-Hao Chang (Darby Chang) 1 Tree 2 A Tree Structure A tree structure means that the data are organized so that items of information are related by branches 3 Definition

More information

Advanced Set Representation Methods

Advanced Set Representation Methods Advanced Set Representation Methods AVL trees. 2-3(-4) Trees. Union-Find Set ADT DSA - lecture 4 - T.U.Cluj-Napoca - M. Joldos 1 Advanced Set Representation. AVL Trees Problem with BSTs: worst case operation

More information

tree nonlinear Examples

tree nonlinear Examples The Tree ADT Objectives Define trees as data structures Define the terms associated with trees Discuss tree traversal algorithms Discuss a binary tree implementation Examine a binary tree example 10-2

More information

CSE 100 Advanced Data Structures

CSE 100 Advanced Data Structures CSE 100 Advanced Data Structures Overview of course requirements Outline of CSE 100 topics Review of trees Helpful hints for team programming Information about computer accounts Page 1 of 25 CSE 100 web

More information

CS 8391 DATA STRUCTURES

CS 8391 DATA STRUCTURES DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING QUESTION BANK CS 8391 DATA STRUCTURES UNIT- I PART A 1. Define: data structure. A data structure is a way of storing and organizing data in the memory for

More information

Trees. Chapter 6. strings. 3 Both position and Enumerator are similar in concept to C++ iterators, although the details are quite different.

Trees. Chapter 6. strings. 3 Both position and Enumerator are similar in concept to C++ iterators, although the details are quite different. Chapter 6 Trees In a hash table, the items are not stored in any particular order in the table. This is fine for implementing Sets and Maps, since for those abstract data types, the only thing that matters

More information

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

Computational Optimization ISE 407. Lecture 16. Dr. Ted Ralphs Computational Optimization ISE 407 Lecture 16 Dr. Ted Ralphs ISE 407 Lecture 16 1 References for Today s Lecture Required reading Sections 6.5-6.7 References CLRS Chapter 22 R. Sedgewick, Algorithms in

More information

APJ ABDUL KALAM TECHNOLOGICAL UNIVERSITY THIRD SEMESTER B.TECH DEGREE EXAMINATION, JULY 2017 CS205: DATA STRUCTURES (CS, IT)

APJ ABDUL KALAM TECHNOLOGICAL UNIVERSITY THIRD SEMESTER B.TECH DEGREE EXAMINATION, JULY 2017 CS205: DATA STRUCTURES (CS, IT) D B3D042 Pages: 2 Reg. No. Name: APJ ABDUL KALAM TECHNOLOGICAL UNIVERSITY THIRD SEMESTER B.TECH DEGREE EXAMINATION, JULY 2017 Max. Marks: 100 CS205: DATA STRUCTURES (CS, IT) PART A Answer all questions.

More information

Elementary Data Structures 2

Elementary Data Structures 2 Elementary Data Structures Priority Queues, & Dictionaries Priority Queues Sell 00 IBM $ Sell 300 IBM $0 Buy 00 IBM $9 Buy 400 IBM $8 Priority Queue ADT A priority queue stores a collection of items An

More information

References and Homework ABSTRACT DATA TYPES; LISTS & TREES. Abstract Data Type (ADT) 9/24/14. ADT example: Set (bunch of different values)

References and Homework ABSTRACT DATA TYPES; LISTS & TREES. Abstract Data Type (ADT) 9/24/14. ADT example: Set (bunch of different values) 9// References and Homework Text: Chapters, and ABSTRACT DATA TYPES; LISTS & TREES Homework: Learn these List methods, from http://docs.oracle.com/javase/7/docs/api/java/util/list.html add, addall, contains,

More information

Recitation 9. Prelim Review

Recitation 9. Prelim Review Recitation 9 Prelim Review 1 Heaps 2 Review: Binary heap min heap 1 2 99 4 3 PriorityQueue Maintains max or min of collection (no duplicates) Follows heap order invariant at every level Always balanced!

More information

CHENNAI MATHEMATICAL INSTITUTE M.Sc. / Ph.D. Programme in Computer Science

CHENNAI MATHEMATICAL INSTITUTE M.Sc. / Ph.D. Programme in Computer Science CHENNAI MATHEMATICAL INSTITUTE M.Sc. / Ph.D. Programme in Computer Science Entrance Examination, 5 May 23 This question paper has 4 printed sides. Part A has questions of 3 marks each. Part B has 7 questions

More information

CSci 231 Final Review

CSci 231 Final Review CSci 231 Final Review Here is a list of topics for the final. Generally you are responsible for anything discussed in class (except topics that appear italicized), and anything appearing on the homeworks.

More information

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

Section 1: True / False (1 point each, 15 pts total) Section : True / False ( point each, pts total) Circle the word TRUE or the word FALSE. If neither is circled, both are circled, or it impossible to tell which is circled, your answer will be considered

More information

Lecture Summary CSC 263H. August 5, 2016

Lecture Summary CSC 263H. August 5, 2016 Lecture Summary CSC 263H August 5, 2016 This document is a very brief overview of what we did in each lecture, it is by no means a replacement for attending lecture or doing the readings. 1. Week 1 2.

More information

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

CSE 373 Autumn 2010: Midterm #1 (closed book, closed notes, NO calculators allowed) Name: Email address: CSE 373 Autumn 2010: Midterm #1 (closed book, closed notes, NO calculators allowed) Instructions: Read the directions for each question carefully before answering. We may give partial

More information

CS 151 Name Final Exam December 17, 2014

CS 151 Name Final Exam December 17, 2014 Note that there are 10 equally-weighted qeustions. CS 151 Name Final Exam December 17, 2014 1. [20 points] Here is a list of data: 4 2 18 1 3 7 9 0 5. For each of the following structures I will walk through

More information