id
int64
0
25.6k
text
stringlengths
0
4.59k
21,200
good way to satisfy such queries for examplecalling successors(kon query key (ordpvd may : )could result in an iterator with the following entries((ordpvd may : )(aa : $ )((ordpvd may : )(aa : $ )((ordpvd may : )(aa : $ )((ordpvd may : )(aa : $ )maxima sets life is full of trade-offs we often have to trade off desired performance measure against corresponding cost supposefor the sake of an examplewe are interested in maintaining database rating automobiles by their maximum speeds and their cost we would like to allow someone with certain amount to spend to query our database to find the fastest car they can possibly afford we can model such trade-off problem as this by using key-value pair to model the two parameters that we are trading offwhich in this case would be the pair (costspeedfor each car notice that some cars are strictly better than other cars using this measure for examplea car with cost-speed pair ( , , is strictly better than car with cost-speed pair ( , , at the same timethere are some cars that are not strictly dominated by another car for examplea car with cost-speed pair ( , may be better or worse than car with costspeed pair ( , )depending on how much money we have to spend (see figure figure illustrating the cost-performance tradeoff with key-value pairs represented by points in the plane notice that point is strictly better than points cdand ebut may be better or worse than points abfgand hdepending on the price we are willing to pay thusif we were to add to our setwe could remove the points cdand ebut not the others
21,201
and pair (abis called maximum pair if it is not dominated by any other pairs we are interested in maintaining the set of maxima of collection of price-performance pairs that iswe would like to add new pairs to this collection (for examplewhen new car is introduced)and we would like to query this collection for given dollar amount to find the fastest car that costs no more than dollars we can store the set of maxima pairs in an ordered dictionarydordered by costso that the cost is the key field and performance (speedis the value field we can then implement operations add( , )which adds new cost-performance pair ( , )and best( )which returns the best pair with cost at most cas shown in code fragment code fragment the methods for maintaining set of maximaas implemented with an ordered dictionary
21,202
(lognexpected time and add( ,pupdates in (( )log nexpected timewhere is the number of points removed thuswe are able to achieve good running times for the methods that maintain our set of maxima exercises for source code and help with exercisesplease visit java datastructures net reinforcement -
21,203
initially empty map that is implemented with listr- describe how to use map to implement the dictionary adtassuming that the user does not attempt to insert entries with the same key - describe how an ordered list implemented as doubly linked list could be used to implement the map adt - what would be good hash code for vehicle identification numberthat is string of numbers and letters of the form " xx xx ,where " represents digit and an "xrepresents letterr- draw the -entry hash table that results from using the hash functionh( ( mod to hash the keys , and assuming collisions are handled by chaining - what is the result of the previous exerciseassuming collisions are handled by linear probingr- show the result of exercise - assuming collisions are handled by quadratic probingup to the point where the method fails - what is the result of exercise - when collisions are handled by double hashing using the secondary hash function '( ( mod ) - give pseudo-code description of an insertion into hash table that uses quadratic probing to resolve collisionsassuming we also use the trick of replacing deleted entries with special "deactivated entryobject -
21,204
be included in the hash table implementation of code fragments - explain how to modify class hashtablemap given in code fragments so that it implements the dictionary adt instead of the map adt - show the result of rehashing the hash table shown in figure into table of size using the new hash function ( mod - argue why hash table is not suited to implement an ordered dictionary - what is the worst-case time for putting entries in an initially empty hash tablewith collisions resolved by chainingwhat is the best caser- draw an example skip list that results from performing the following series of operations on the skip list shown in figure remove( )insert( , )insert( , )remove( record your coin flipsas well - give pseudo-code description of the remove operation in skip list - what is the expected running time of the methods for maintaining maxima set if we insert pairs such that each pair has lower cost and performance than one before itwhat is contained in the ordered dictionary at the end of this series of operationswhat if each pair had lower cost and higher performance than the one before itr- argue why location-aware entries are not really needed for dictionary implemented with good hash table creativity -
21,205
user may attempt to insert entries with the same key - suppose we are given two ordered search tables and teach with entries (with and being implemented with arraysdescribe an (log )-time algorithm for finding the kth smallest key in the union of the keys from and (assuming no duplicatesc- give an (logn)-time solution for the previous problem - design variation of binary search for performing operation findall(kin dictionary implemented with an ordered search tableand show that it runs in time (logn )where is the number of elements in the dictionary and is the size of the iterator returned - describe the changes that must be made in the pseudo-code descriptions of the fundamental dictionary methods when we implement dictionary with hash table such that collisions are handled via separate chainingbut we add the space optimization that if bucket stores just single entrythen we simply have the bucket reference that entry directly - the hash table dictionary implementation requires that we find prime number between number and number implement method for finding such prime by using the sieve algorithm in this algorithmwe allocate cell boolean array asuch that cell is associated with the integer we then initialize the array cells to all be "trueand we "mark off all the cells that are multiples of and so on this process can stop after it reaches number larger than (hintconsider bootstrapping method for finding the primes up to - describe how to perform removal from hash table that uses linear probing to resolve collisions where we do not use special marker to represent deleted elements that iswe must rearrange the contents so that it appears that the removed entry was never inserted in the first place
21,206
given collection of cost-performance pairs ( , )describe an algorithm for finding the maxima pairs of in ( logntime - the quadratic probing strategy has clustering problem related to the way it looks for open slots namelywhen collision occurs at bucket ( )it checks buckets [( (kj mod ]for , show that mod will assume at most ( )/ distinct valuesfor primeas ranges from to as part of this justificationnote that mod ( ) mod for all better strategy is to choose prime such that mod and then to check the bucketsa[( ( + mod nas ranges from to ( )/ alternating between plus and minus show that this alternate version is guaranteed to check every bucket in - show that the methods above(pand prev(pare not actually needed to efficiently implement dictionary using skip list that iswe can implement entry insertion and removal in skip list using strictly top-downscan-forward approachwithout ever using the above or prev methods (hintin the insertion algorithmfirst repeatedly flip the coin to determine the level where you should start inserting the new entry - describe how to implement successors(kin an ordered dictionary realized using an ordered search table what is its running timec- repeat the previous exercise using skip list what is the expected running time in this casec- suppose that each row of an array consists of ' and ' such thatin any row of aall the ' come before any ' in that row assuming is already
21,207
counting the number of ' in - describe an efficient dictionary structure for storing entries that have an associated set of keys that comes from total order that isthe set of keys is smaller than the number of entries your structure should perform operation find all in (logr sexpected timewhere is the number of entries returnedoperation entries(in (ntimeand the remaining operations of the dictionary adt in (logrexpected time - describe an efficient dictionary structure for storing entries whose keys have distinct hash codes your structure should perform operation findall in ( sexpected timewhere is the number of entries returnedoperation entries(in (ntimeand the remaining operations of the dictionary adt in ( expected time - describe an efficient data structure for implementing the bag adtwhich supports method add( )for adding an element to the bagand method remove()which removes an arbitrary element in the bag show that both of these methods can be done in ( time - describe how to modify the skip list data structure to support the method atindex( )which returns the position of the element in the "bottomlist at index ifor [ show that your implementation of this method runs in (lognexpected time projects - implement class that implements the dictionary adt by adapting the java util hashmap class - implement the map adt with hash table with separate chaining collision handling (do not adapt any java util classesp-
21,208
- implement the methods of the ordered dictionary adt using skip list - extend the previous project by providing graphical animation of the skip list operations visualize how entries move up the skip list during insertions and are linked out of the skip list during removals alsoin search operationvisualize the scan-forward and drop-down actions - implement dictionary that supports location-aware entries by means of an ordered list - perform comparative analysis that studies the collision rates for various hash codes for character stringssuch as various polynomial hash codes for different values of the parameter use hash table to determine collisionsbut only count collisions where different strings map to the same hash code (not if they map to the same location in this hash tabletest these hash codes on text files found on the internet - perform comparative analysis as in the previous exercise but for -digit telephone numbers instead of character strings - design java class that implements the skip list data structure use this class to create implementations of both the map and dictionary adtsincluding location-aware methods for the dictionary notes hashing is well-studied technique the reader interested in further study is encouraged to explore the book by knuth [ ]as well as the book by vitter and chen [ interestinglybinary search was first published in but was not published in fully correct form until for further discussions on lessons learnedplease see papers by bentley [ and levisse [ skip lists were introduced by pugh [ our analysis of skip lists is simplification of presentation given by motwani and raghavan [ for more in-depth analysis of skip lists
21,209
structures literature [ exercise - was contributed by james lee we use star to indicate sections containing material more advanced than the material in the rest of the this material can be considered optional in first reading search trees contents binary search trees searching
21,210
update operations java implementation avl trees update operations java implementation splay trees splaying when to splay
21,211
( trees multi-way search trees update operations for ( , trees red-black trees update operations java implementation exercises java datastructures net
21,212
binary search trees all of the structures we discuss in this are search treesthat istree data structures that can be used to implement dictionary let usthereforebegin by briefly reviewing the fundamental methods of the dictionary adtfind( )return an entry with key kif it exists findall( )return an iterable collection of all entries with keys equal to insert( , )insert an entry with key and value remove( )remove an entry eand return it removeall( )remove all entries with key kreturning an iterator of their values method find returns null if is not found the ordered dictionary adt includes some additional methods for searching through predecessors and successors of key or entrybut their performance is similar to that of find so we will be focusing on find as the primary search operation in this binary trees are an excellent data structure for storing the entries of dictionaryassuming we have an order relation defined on the keys as mentioned previously (section ) binary search tree is binary tree such that each internal node of stores an entry ( ,xsuch thatkeys stored at nodes in the left subtree of are less than or equal to keys stored at nodes in the right subtree of are greater than or equal to as we show belowthe keys stored at the nodes of provide way of performing search by making comparison at each internal node vwhich can stop at or continue at ' left or right child thuswe take the view here that binary search trees are nonempty proper binary trees that iswe store entries only at the internal nodes of binary search treeand the external nodes serve only as "placeholders this approach simplifies several of our search and update algorithms incidentallywe could have allowed for improper binary search treeswhich have better space usagebut at the expense of more complicated search and update methods independent of whether we view binary search trees as proper or notthe important property of binary search tree is the realization of an ordered dictionary (or mapthat isa binary search tree should hierarchically represent an ordering of its keysusing relationships between parent and children specificallyan inorder traversal (section of the nodes of binary search tree should visit the keys in nondecreasing order
21,213
searching to perform operation find(kin dictionary that is represented with binary search tree twe view the tree as decision tree (recall figure in this casethe question asked at each internal node of is whether the search key is less thanequal toor greater than the key stored at node vdenoted with key(vif the answer is "smaller,then the search continues in the left subtree if the answer is "equal,then the search terminates successfully if the answer is "greater,then the search continues in the right subtree finallyif we reach an external nodethen the search terminates unsuccessfully (see figure figure (aa binary search tree representing dictionary with integer keys(bnodes of visited when executing operations find( (successfuland find( (unsuccessfulon for simplicitywe show keys but entry values we describe this approach in detail in code fragment given search key and node of tthis methodtreesearchreturns node (positionw of the subtree (vof rooted at vsuch that one of the following occursw is an internal node and ' entry has key equal to is an external node representing ' proper place in an inorder traversal of ( )but is not key contained in (vthusmethod find(kcan be performed by calling treesearch(kt root()let be the node of returned by this call if is an internal nodethen we return ' entryotherwisewe return null code fragment search tree recursive search in binary
21,214
the analysis of the worst-case running time of searching in binary search tree is simple algorithm treesearch is recursive and executes constant number of primitive operations for each recursive call each recursive call of treesearch is made on child of the previous node that istreesearch is called on the nodes of path of that starts at the root and goes down one level at time thusthe number of such nodes is bounded by where is the height of in other wordssince we spend ( time per node encountered in the searchmethod find on dictionary runs in (htimewhere is the height of the binary search tree used to implement (see figure figure illustrating the running time of searching in binary search tree the figure uses standard visualization shortcuts of viewing binary search tree as big triangle and path from the root as zig-zag line
21,215
findall(kin time ( )where is the number of entries returned howeverthis method is slightly more complicatedand the details are left as an exercise ( - admittedlythe height of can be as large as nbut we expect that it is usually much smaller indeedwe will show how to maintain an upper bound of (lognon the height of search tree in section before we describe such schemehoweverlet us describe implementations for dictionary update methods update operations binary search trees allow implementations of the insert and remove operations using algorithms that are fairly straightforwardbut not trivial insertion let us assume proper binary tree supports the following update operationinsertatexternal( , )insert the element at the external node vand expand to be internalhaving new (emptyexternal node children
21,216
given this methodwe perform insert( ,xfor dictionary implemented with binary search tree by calling treeinsert( , , root())which is given in code fragment code fragment recursive algorithm for insertion in binary search tree this algorithm traces path from ' root to an external nodewhich is expanded into new internal node accommodating the new entry an example of insertion into binary search tree is shown in figure figure insertion of an entry with key into the search tree of figure finding the position to insert is shown in ( )and the resulting tree is shown in (bremoval
21,217
with binary search tree is bit more complexsince we do not wish to create any "holesin the tree we assumein this casethat proper binary tree supports the following additional update operationremoveexternal( )remove an external node and its parentreplacing ' parent with ' siblingan error occurs if is not external given this operationwe begin our implementation of operation remove(kof the dictionary adt by calling treesearch(kt root()on to find node of storing an entry with key equal to if treesearch returns an external nodethen there is no entry with key in dictionary dand we return null (and we are doneif treesearch returns an internal node insteadthen stores an entry we wish to removeand we distinguish two cases (of increasing difficulty)if one of the children of node is an external nodesay node zwe simply remove and from by means of operation removeexternal(zon this operation restructures by replacing with the sibling of zremoving both and from (see figure if both children of node are internal nodeswe cannot simply remove the node from tsince this would create "holein insteadwe proceed as follows (see figure )we find the first internal node that follows in an inorder traversal of node is the left-most internal node in the right subtree of wand is found by going first to the right child of and then down from therefollowing left children alsothe left child of is the external node that immediately follows node in the inorder traversal of we save the entry stored at in temporary variable tand move the entry of into this action has the effect of removing the former entry stored at we remove nodes and from by calling removeexternal(xon this action replaces with ' siblingand removes both and from we return the entry previously stored at wwhich we had saved in the temporary variable as with searching and insertionthis removal algorithm traverses path from the root to an external nodepossibly moving an entry between two nodes of this pathand then performs removeexternal operation at that external node
21,218
figure bwhere the entry to remove (with key is stored at node (wwith an external child(abefore the removal(bafter the removal figure removal from the binary search tree of figure bwhere the entry to remove (with key is stored at node (wwhose children are both internal(abefore the removal(bafter the removal performance of binary search tree the analysis of the searchinsertionand removal algorithms are similar we spend ( time at each node visitedandin the worst casethe number of nodes visited is proportional to the height of thusin dictionary implemented with binary search tree tthe findinsertand remove methods run in
21,219
implementation of dictionary with entries only if the height of is small in the best caset has height log( which yields logarithmic-time performance for all the dictionary operations in the worst casehowevert has height nin which case it would look and feel like an ordered list implementation of dictionary such worst-case configuration arisesfor exampleif we insert series of entries with keys in increasing or decreasing order (see figure figure example of binary search tree with linear heightobtained by inserting entries with keys in increasing order the performance of dictionary implemented with binary search tree is summarized in the following proposition and in table proposition binary search tree with height for key-value entries uses (nspace and executes the dictionary adt operations with the following running times operationssize andisempty each take ( time operationsfindinsertandremove each take (htime the operationfindall takes ( stimewhere is the size of the collection returned table running times of the main methods of dictionary realized by binary search tree we denote the current height of the tree with and the size of the collection returned by findall with the space usage is ( )where is the number of entries stored in the dictionary
21,220
time size,isempty ( findinsertremove (hfindall ( snote that the running time of search and update operations in binary search tree varies dramatically depending on the tree' height we can nevertheless take comfort thaton averagea binary search tree with keys generated from random series of insertions and removals of keys has expected height (lognsuch statement requires careful mathematical language to precisely define what we mean by random series of insertions and removalsand sophisticated probability theory to provehenceits justification is beyond the scope of this book neverthelesskeep in mind the poor worst-case performance and take care in using standard binary search trees in applications where updates are not random there areafter allapplications where it is essential to have dictionary with fast worst-case search and update times the data structures presented in the next sections address this need java implementation in code fragments through we describe binary search tree classbinarysearchtreewhich stores objects of class bstentry (implementing the entry interfaceat its nodes class binarysearchtree extends class linked binarytree from code fragments through thus taking advantage of code reuse this class makes use of several auxiliary methods to do much of the heavy lifting the auxiliary method treesearchbased on the treesearch algorithm (code fragment )is invoked by the findfindalland insert methods we use recursive addall method as the main engine for the findall(kmethodin that it performs an inorder traversal of all the entries with keys equal to (although not using the fast algorithmsince it performs failed search for every entry it findswe use two additional update methodsinsertatexternalwhich inserts new entry at an external nodeand removeexternalwhich removes an external node and its parent
21,221
its update methods inform any moved bstentry objects of their new positions we also use several simple auxiliary methods for accessing and testing datasuch as checkkeywhich checks if key is valid (albeit using fairly simple rule in this casewe also use an instance variableactionposwhich stores the position where the most recent searchinsertionor removal ended this instance variable is not necessary to the implementation of binary search treebut is useful to classes that will extend binarysearchtree (see code fragments and to identify the position where the previous searchinsertionor removal has taken place position action pos has the intended meaning provided it is used right after executing the method findinsertor remove code fragment class binarysearchtree (continues in code fragment
21,222
(continues in code fragment
21,223
class binarysearchtree (continued from code fragment
21,224
avl trees in the previous sectionwe discussed what should be an efficient dictionary data structurebut the worst-case performance it achieves for the various operations is linear timewhich is no better than the performance of listand array-based dictionary implementations (such as unordered lists and search tables discussed in in this sectionwe describe simple way of correcting this problem so as to achieve logarithmic time for all the fundamental dictionary operations definition of an avl tree the simple correction is to add rule to the binary search tree definition that will maintain logarithmic height for the tree the rule we consider in this section is the following height-balance propertywhich characterizes the structure of binary search tree in terms of the heights of its internal nodes (recall from section that the height of node in tree is the length of longest path from to an external node)height-balance propertyfor every internal node of tthe heights of the children of differ by at most any binary search tree that satisfies the height-balance property is said to be an avl treenamed after the initials of its inventorsadel'son-vel'skii and landis an example of an avl tree is shown in figure figure an example of an avl tree the keys of the entries are shown inside the nodesand the heights of the nodes are shown next to the nodes
21,225
avl tree is itself an avl tree the height-balance property has also the important consequence of keeping the height smallas shown in the following proposition proposition the height of an avl tree storing entries is (lognjustificationinstead of trying to find an upper bound on the height of an avl tree directlyit turns out to be easier to work on the "inverse problemof finding lower bound on the minimum number of internal nodes (hof an avl tree with height we will show that (hgrows at least exponentially from thisit will be an easy step to derive that the height of an avl tree storing entries is (lognto start withnotice that ( and ( because an avl tree of height must have at least one internal node and an avl tree of height must have at least two internal nodes nowfor > an avl tree with height and the minimum number of nodes is such that both its subtrees are avl trees with the minimum number of nodesone with height and the other with height taking the root into accountwe obtain the following formula that relates (hto ( and ( )for > ( ( - ( - ( at this pointthe reader familiar with the properties of fibonacci progressions (section and exercise - will already see that (his function exponential in for the rest of the readerswe will proceed with our reasoning formula implies that (his strictly increasing function of thuswe know that ( ( replacing ( with ( in formula and dropping the we getfor > ( * ( ( formula indicates that (hat least doubles each time increases by which intuitively means that (hgrows exponentially to show this fact in formal waywe apply formula repeatedlyyielding the following series of inequalitiesn( * ( * ( * (
21,226
( that isn( ( )for any integer isuch that > since we already know the values of ( and ( )we pick so that is equal to either or that iswe pick by substituting the above value of in formula we obtainfor > ( by taking logarithms of both sides of formula we obtain log (hh/ from which we get logn( ( which implies that an avl tree storing entries has height at most logn by proposition and the analysis of binary search trees given in section the operations find and findallin dictionary implemented with an avl treerun in time (lognand (logn )respectivelywhere is the number of entries in the dictionary and is the size of the collection returned of coursewe still have to show how to maintain the height-balance property after an insertion or removal update operations
21,227
search treesbut with avl trees we must perform additional computations insertion an insertion in an avl tree begins as in an insert operation described in section for (simplebinary search tree recall that this operation always inserts the new entry at node in that was previously an external nodeand it makes become an internal node with operation insertatexternal that isit adds two external node children to this action may violate the heightbalance propertyhoweverfor some nodes increase their heights by one in particularnode wand possibly some of its ancestorsincrease their heights by one thereforelet us describe how to restructure to restore its height balance given binary search tree twe say that an internal node of is balanced if the absolute value of the difference between the heights of the children of is at most and we say that it is unbalanced otherwise thusthe height-balance property characterizing avl trees is equivalent to saying that every internal node is balanced suppose that satisfies the height-balance propertyand hence is an avl treeprior to our inserting the new entry as we have mentionedafter performing the operation insertatexternal on tthe heights of some nodes of tincluding wincrease all such nodes are on the path of from to the root of tand these are the only nodes of that may have just become unbalanced (see figure of courseif this happensthen is no longer an avl treehencewe need mechanism to fix the "unbalancethat we have just caused figure an example insertion of an entry with key in the avl tree of figure (aafter adding new node for key the nodes storing keys and become unbalanced(ba trinode restructuring restores the height-balance property we show the heights of nodes next to themand we identify the nodes xyand participating in the trinode restructuring
21,228
"search-and-repairstrategy in particularlet be the first node we encounter in going up from toward the root of such that is unbalanced (see figure alsolet denote the child of with higher height (and note that node must be an ancestor of wfinallylet be the child of with higher height (there cannot be tie and node must be an ancestor of walsonode is grandchild of and could be equal to since became unbalanced because of an insertion in the subtree rooted at its child ythe height of is greater than its sibling we now rebalance the subtree rooted at by calling the trinode restructuring methodrestructure( )given in code fragment and illustrated in figures and trinode restructuring temporarily renames the nodes xyand as aband cso that precedes and precedes in an inorder traversal of there are four possible ways of mapping xyand to aband cas shown in figure which are unified into one case by our relabeling the trinode restructuring then replaces with the node called bmakes the children of this node be and cand makes the children of and be the four previous children of xyand (other than andywhile maintaining the inorder relationships of all the nodes in code fragment the trinode restructuring operation in binary search tree
21,229
called rotationbecause of the geometric way we can visualize the way it changes if ythe trinode restructuring method is called single rotationfor it can be visualized as "rotatingy over (see figure and otherwiseif xthe trinode restructuring operation is called double rotationfor it can be visualized as first "rotatingx over and then over (see figure and dand figure some computer researchers treat these two kinds of rotations as separate methodseach with two symmetric types we have chosenhoweverto unify these four types of rotations into single trinode restructuring operation no matter how we view itthoughthe trinode restructuring method modifies parentchild relationships of ( nodes in twhile preserving the inorder traversal ordering of all the nodes in in addition to its order-preserving propertya trinode restructuring changes the heights of several nodes in tso as to restore balance recall that we execute the method restructure(xbecause zthe grandparent of xis unbalanced moreoverthis unbalance is due to one of the children of now having too large height relative to the height of ' other child as result of rotationwe move up the "tallchild of while pushing down the "shortchild of thusafter performing restructure( )all the nodes in the subtree now rooted at the node we called are balanced (see figure thuswe restore the heightbalance property locally at the nodes xyand in additionsince after performing the new entry insertion the subtree rooted at replaces the one formerly rooted at zwhich was taller by one unitall the ancestors of that were formerly unbalanced become balanced (see figure (the justification of this fact is left as exercise - thereforethis one restructuring also restores the height-balance property globally
21,230
restructuring operation (code fragment )(aand (ba single rotation(cand (da double rotation
21,231
as was the case for the insert dictionary operationwe begin the implementation of the remove dictionary operation on an avl tree by using the algorithm for performing this operation on regular binary search tree the added difficulty in using this approach with an avl tree is that it may violate the height-balance property in particularafter removing an internal node with operation remove external and elevating one of its children into its placethere may be an unbalanced node in on the path from the parent of the previously removed node to the root of (see figure in factthere can be one such unbalanced node at most (the justification of this fact is left as exercise - figure removal of the entry with key from the avl tree of figure (aafter removing the node storing key the root becomes unbalanced(ba (singlerotation restores the heightbalance property as with insertionwe use trinode restructuring to restore balance in the tree in particularlet be the first unbalanced node encountered going up from toward the root of alsolet be the child of with larger height (note that node is the child of that is not an ancestor of )and let be the child of defined as followsif one of the children of is taller than the otherlet be the taller child of yelse (both children of have the same height)let be the child of on the same side as (that isif is left childlet be the left child of yelse let be the right child of yin any casewe then perform restructure(xoperationwhich restores the height-balance property locallyat the subtree that was formerly rooted at and is now rooted at the node we temporarily called (see figure unfortunatelythis trinode restructuring may reduce the height of the subtree rooted at by which may cause an ancestor of to become unbalanced soafter rebalancing zwe continue walking up looking for unbalanced nodes if we
21,232
continue marching up looking for moreall the way to the root stillsince the height of is (logn)where is the number of entriesby proposition (logntrinode restructurings are sufficient to restore the height-balance property performance of avl trees we summarize the analysis of the performance of an avl tree as follows operations findinsertand remove visit the nodes along root-to-leaf path of tpluspossiblytheir siblingsand spend ( time per node thussince the height of is (lognby proposition each of the above operations takes (logntime we leave the implementation and analysis of an efficient version of the operation findall as an interesting exercise in table we summarize the performance of dictionary implemented with an avl tree we illustrate this performance in figure table performance of an -entry dictionary realized by an avl treewhere denotes the size of the collection returned by findall the space usage is (noperation time sizeisempty ( findinsertremove (lognfindall (logn sfigure illustrating the running time of searches and updates in an avl tree the time performance is ( per levelbroken into down phasewhich typically involves searchingand an up phasewhich
21,233
performing local trinode restructurings (rotationsjava implementation let us now turn to the implementation details and analysis of using an avl tree with internal nodes to implement an ordered dictionary of entries the insertion and removal algorithms for require that we are able to perform trinode restructurings and determine the difference between the heights of two sibling nodes regarding restructuringswe now need to make sure our underlying implementation of binary search tree includes the method restructure( )which performs tri-node restructuring operation (code fragment it is easy to see that restructure operation can be performed in ( time if is implemented with linked structure (section in our casewe assume that the binarysearchtree class includes this method regarding height informationwe can explicitly store the height of each internal nodevin the node itself alternativelywe can store the balance factor of at vwhich is defined as the height of the left child of minus the height of the right child of thusthe balance factor of is always equal to - or except during an insertion or removalwhen it may become temporarily equal to - or + during the execution of an insertion or removalthe heights and balance factors of (lognnodes are affected and can be maintained in (logntime
21,234
implementing dictionary using an avl tree (assuming the parent class includes an implementation of the restructure methodthis class extends binarysearchtree (code fragments and includes nested classavlnodewhich extends the btnode class used to represent the nodes of binary tree the avlnode class defines an additional instance variable heightrepresenting the height of the node we get our binary tree to use this node class instead of the btnode class simply by overriding the createnode methodwhich is used exclusively to create new binary tree nodes class avltree inherits methods sizeisemptyfindand findall from its superclassbinarysearchtreebut overrides methods insert and remove to keep the search tree balanced method insert (code fragment begins by calling the superclass' insert methodwhich inserts the new entry and assigns the insertion position (for examplethe node storing key in figure to the instance variable actionpos the auxiliary method rebalance is then used to traverse the path from the insertion position to the root this traversal updates the heights of all the nodes visitedand performs trinode restructuring if necessary similarlymethod remove (code fragment begins by calling the superclass' remove methodwhich performs the removal of the entry and assigns the position replacing the deleted one to instance variable actionpos the auxiliary method rebalance is then used to traverse the path from the removed position to the rootperforming any needed restructurings code fragment constructor and auxiliary methods of class avltree
21,235
tallerchild and rebalance and dictionary methods insert and remove of class avltree
21,236
splay trees another way we can implement the fundamental dictionary operations is to use balanced search tree data structure known as splay tree this structure is conceptually quite different from the other balanced search trees we discuss in this for splay tree does not use any explicit rules to enforce its balance insteadit applies certain move-to-root operationcalled splayingafter every accessin order to keep the search tree balanced in an amortized sense the splaying operation is performed at the bottom-most node reached during an insertiondeletionor even search the surprising thing about splaying is that it allows us to guarantee an amortized running timefor insertionsdeletionsand searchesthat is logarithmic the structure of splay tree is simply binary search tree in factthere are no additional heightbalanceor color labels that we associate with the nodes of this tree splaying given an internal node of binary search tree twe splay by moving to the root of through sequence of restructurings the particular restructurings we perform are importantfor it is not sufficient to move to the root of by just any sequence of restructurings the specific operation we perform to move up depends upon the relative positions of xits parent yand (if it existsx' grandparent there are three cases that we consider zig-zigthe node and its parent are both left children or both right children (see figure we replace by xmaking child of and child of ywhile maintaining the inorder relationships of the nodes in figure zig-zig(abefore(bafter there is another symmetric configuration where and are left children
21,237
in this casewe replace by and make have and as its childrenwhile maintaining the inorder relationships of the nodes in figure zig-zag(abefore(bafter there is another symmetric configuration where is right child and is left child zigx does not have grandparent (or we are not considering ' grandparent for some reason(see figure in this casewe rotate over ymaking ' children be the node and one of ' former children wso as to maintain the relative inorder relationships of the nodes in figure zig(abefore(bafter there is another symmetric configuration where and are left children
21,238
when has parent but not grandparent splaying step consists of repeating these restructurings at until becomes the root of note that this is not the same as sequence of simple rotations that brings to the root an example of the splaying of node is shown in figures and figure example of splaying node(asplaying the node storing starts with zig-zag(bafter the zig-zag(cthe next step is zig-zig (continues in figure
21,239
zig-zig(ethe next step is again zig-zig(fafter the zig-zig (continued from figure
21,240
when to splay the rules that dictate when splaying is performed are as followswhen searching for key kif is found at node xwe splay xelse we splay the parent of the external node at which the search terminates unsuccessfully for examplethe splaying in figures and would be performed after searching successfully for key or unsuccessfully for key when inserting key kwe splay the newly created internal node where gets inserted for examplethe splaying in figures and would be performed if were the newly inserted key we show sequence of insertions in splay tree in figure figure sequence of insertions in splay tree(ainitial tree(bafter inserting (cafter splaying(dafter inserting (eafter splaying(fafter inserting (gafter splaying
21,241
when deleting key kwe splay the parent of the node that gets removedthat isw is either the node storing or one of its descendents (recall the removal algorithm for binary search trees an example of splaying following deletion is shown in figure figure deletion from splay tree(athe deletion of from node is performed by moving to the key of the right-most internal node vin the left subtree of rdeleting vand splaying the parent of (bsplaying starts with zig-zig(cafter the zig-zig(dthe next step is zig(eafter the zig
21,242
amortized analysis of splaying
21,243
of decreases by one thusif has depth dsplaying consists of sequence of / zig-zigs and/or zig-zagsplus one final zig if is odd since single zig-zigzig-zagor zig affects constant number of nodesit can be done in ( time thussplaying node in binary search tree takes time ( )where is the depth of in in other wordsthe time for performing splaying step for node is asymptotically the same as the time needed just to reach that node in top-down search from the root of worst case time in the worst casethe overall running time of searchinsertionor deletion in splay tree of height is ( )since the node we splay might be the deepest node in the tree moreoverit is possible for to be as large as nas shown in figure thusfrom worst-case point of viewa splay tree is not an attractive data structure in spite of its poor worst-case performancea splay tree performs well in an amortized sense that isin sequence of intermixed searchesinsertionsand deletionseach operation takes on average logarithmic time we perform the amortized analysis of splay trees using the accounting method amortized performance of splay trees for our analysiswe note that the time for performing searchinsertionor deletion is proportional to the time for the associated splaying so let us consider only splaying time let be splay tree with keysand let be node of we define the size (vof as the number of nodes in the subtree rooted at note that this definition implies that the size of an internal node is one more than the sum of the sizes of its two children we define the rank (vof node as the logarithm in base of the size of vthat isr(vlog( ( )clearlythe root of has the maximum size ( and the maximum ranklog( + )while each external node has size and rank we use cyber-dollars to pay for the work we perform in splaying node in tand we assume that one cyber-dollar pays for zigwhile two cyber-dollars pay for zig-zig or zig-zag hencethe cost of splaying node at depth is cyberdollars we keep virtual account storing cyber-dollars at each internal node of note that this account exists only for the purpose of our amortized analysisand does not need to be included in data structure implementing the splay tree an accounting analysis of splaying
21,244
value of the payment will be determined at the end of our analysiswe distinguish three casesif the payment is equal to the splaying workthen we use it all to pay for the splaying if the payment is greater than the splaying workwe deposit the excess in the accounts of several nodes if the payment is less than the splaying workwe make withdrawals from the accounts of several nodes to cover the deficiency we will showin the rest of this sectionthat payment of (logncyber-dollars per operation is sufficient to keep the system workingthat isto ensure that each node keeps nonnegative account balance cyber-dollar invariant for splaying we use scheme in which transfers are made between the accounts of the nodes to ensure that there will always be enough cyber-dollars to withdraw for paying for splaying work when needed in order to use the accounting method to perform our analysis of splayingwe maintain the following invariantbefore and after splayingeach node of has (vcyber-dollars in its account note that the invariant is "financially sound,since it does not require us to make preliminary deposit to endow tree with zero keys let (tbe the sum of the ranks of all the nodes of to preserve the invariant after splayingwe must make payment equal to the splaying work plus the total change in (twe refer to single zigzig-zigor zig-zag operation in splaying as splaying substep alsowe denote the rank of node of before and after splaying substep with '(vand ( )respectively the following proposition gives an upper bound on the change of (tcaused by single splaying substep we will repeatedly use this lemma in our analysis of full splaying of node to the root proposition let be the variation ofr(tcaused by single splaying substep ( zigzig-zigor zig-zagfor node in we have the followingd < ( '( )- ( ))- if the substep is zig-zig or zig-zag < ( '(xr( )if the substep is zig
21,245
and bloga+logb < logc- ( let us consider the change in (tcaused by each type of splaying substep zig-zig(recall figure since the size of each node is one more than the size of its two childrennote that only the ranks of xyand change in zig-zig operationwhere is the parent of and is the parent of alsonote that ( )+ '( < '(xthusby ( )+ '( < '( )- that isr '( < '( )- ( )- this inequality and imply < '( )+( '( )- ( )- )- ( < ( '( )- ( ))- zig-zag(recall figure againby the definition of size and rankonly the ranks of xyand changewhere denotes the parent of and denotes the parent of alsor '(xr(zand ( < (ythus '{xr '{yr '{ )- { )- { )- { < '(yr '( )- ( )- ( < '(yr '( )- ( ( note that '(yn '( < '( )henceby '( )+ '( < '( - thusd < '( )- - ( < ( '( )- ( ))- zig(recall figure in this caseonly the ranks of and changewhere denotes the parent of alsor '(yr(xthus '( )+ '( )- ( )- (
21,246
< ( '( )- ( )proposition let be splay tree with root tand let be the total variation of (tcaused by splaying node at depth we have < ( (tr( ) + justificationsplaying node consists of / splaying substepseach of which is zig-zig or zig-zagexcept possibly the last onewhich is zig if is odd let (xr(xbe the initial rank of xand for plet (xbe the rank of after the ith substep and be the variation of (tcaused by the ith substep by lemma the total variation of (tcaused by splaying is ( (xr ( ) < ( (tr( ) by proposition if we make payment of ( (tr( ) cyber-dollars towards the splaying of node xwe have enough cyber-dollars to maintain the invariantkeeping (vcyber-dollars at each node in tand pay for the entire splaying workwhich costs dollars since the size of the root is its rank (tlog( in additionwe have (xr(tthusthe payment to be made for splaying is (logncyber-dollars to complete our analysiswe have to compute the cost for maintaining the invariant when node is inserted or deleted when inserting new node into splay tree with keysthe ranks of all the ancestors of are increased namelylet be the ancestors of vwhere vv is the parent of - and is the root for ,dlet '( and ( be the size of before and after the insertionrespectivelyand let '( and ( be the rank of before and after the insertionrespectively we have '{ {
21,247
in this ranger '( log( '( )log( ( <log( ( + ) ( + thusthe total variation of (tcaused by the insertion is '( )- ( <log( + thereforea payment of (logncyber-dollars is sufficient to maintain the invariant when new node is inserted when deleting node from splay tree with keysthe ranks of all the ancestors of are decreased thusthe total variation of (tcaused by the deletion is negativeand we do not need to make any payment to maintain the invariant when node is deleted thereforewe may summarize our amortized analysis in the following proposition (which is sometimes called the "balance propositionfor splay trees)proposition consider sequence ofm operations on splay treeeach one searchinsertionor deletionstarting from splay tree with zero keys alsolet ni be the number of keys in the tree after operation iand be the total number of insertions the total running time for performing the sequence of operations is which is ( log nin other wordsthe amortized running time of performing searchinsertionor deletion in splay tree is (logn)where is the size of the splay tree at the time thusa splay tree can achieve logarithmic-timeamortized performance for implementing an ordered dictionary adt this amortized performance matches the worst-case performance of avl trees( , treesand red-black treesbut it does so using simple binary tree that does not need any extra balance information stored at each of its nodes in additionsplay trees have number of other interesting properties that are not shared by these other balanced search trees we explore one such additional property in the following proposition (which is sometimes called the "static optimalityproposition for splay trees)
21,248
each one searchinsertionor deletionstarting from splay tree with zero keys alsolet (idenote the number of times the entry is accessed in the splay treethat isits frequencyand let denote the total number of entries assuming that each entry is accessed at least oncethen the total running time for performing the sequence of operations is we omit the proof of this propositionbut it is not as hard to justify as one might imagine the remarkable thing is that this proposition states that the amortized running time of accessing an entry is (log( / ( )) ( , trees some data structures we discuss in this including ( , treesare multi-way search treesthat istrees with internal nodes that have two or more children thusbefore we define ( , treeslet us discuss multi-way search trees multi-way search trees recall that multi-way trees are defined so that each internal node can have many children in this sectionwe discuss how multi-way trees can be used as search trees recall that the entries that we store in search tree are pairs of the form ( , )where is the key and is the value associated with the key howeverwe do not discuss how to perform updates in multi-way search trees nowsince the details for update methods depend on additional properties we wish to maintain for multi-way treeswhich we discuss in section definition of multi-way search tree let be node of an ordered tree we say that is -node if has children we define multi-way search tree to be an ordered tree that has the following propertieswhich are illustrated in figure aeach internal node of has at least two children that iseach internal node is -node such that each internal -node of with children stores an ordered set of key-value entries ( , )( , )where << let us conventionally define and for each entry ( ,xstored at node in the subtree of rooted at ,dwe have that <= <ki
21,249
keys and +then key stored in the subtree of rooted at child node must be "in betweentwo keys stored at this simple viewpoint gives rise to the rule that -node stores regular keysand it also forms the basis of the algorithm for searching in multi-way search tree by the above definitionthe external nodes of multi-way search do not store any entries and serve only as "placeholders,as has been our convention with binary search trees (section )hencea binary search tree can be viewed as special case of multi-way search treewhere each internal node stores one entry and has two children in additionwhile the external nodes could be nullwe make the simplifying assumption here that they are actual nodes that don' store anything figure (aa multi-way search tree (bsearch path in for key (unsuccessful search)(csearch path in for key (successful search
21,250
there is an interesting relationship between the number of entries and the number of external nodes proposition an -entry multi-way search tree has + external nodes we leave the justification of this proposition as an exercise ( - searching in multi-way tree given multi-way search tree twe note that searching for an entry with key is simple we perform such search by tracing path in starting at the root (see figure and when we are at -node during this searchwe compare the key with the keys stored at if for some ithe search is successfully completed otherwisewe continue the search in the child vi of such that < < (recall that we conventionally define and if we reach an external nodethen we know that there is no entry with key in tand the search terminates unsuccessfully data structures for representing multi-way search trees in section we discuss linked data structure for representing general tree this representation can also be used for multi-way search tree in factin using general tree to implement multi-way search treethe only additional information that we need to store at each node is the set of entries (including keysassociated with that node that iswe need to store with reference to some collection that stores the entries for recall that when we use binary search tree to represent an ordered dictionary dwe simply store reference to single entry at each internal node in using multi-way search tree to represent dwe must store reference to the ordered set of entries associated with at each internal node of this reasoning may at first seem like circular argumentsince we need representation of an ordered dictionary to represent an ordered dictionary we can avoid any circular argumentshoweverby using the bootstrapping techniquewhere we use previous (less advancedsolution to problem to create new (more advancedsolution in this casebootstrapping consists of representing the ordered set associated with each internal node using dictionary data structure that we have previously constructed (for examplea search table based on sorted arrayas shown in section in particularassuming we already have way of implementing ordered dictionarieswe can realize multi-way search tree by taking tree and storing such dictionary at each node of
21,251
we are using it to support the biggerprimary data structure we denote the dictionary stored at node of as (vthe entries we store in (vwill allow us to find which child node to move to next during search operation specificallyfor each node of twith children , and entries ( , )( - , - )we store in the dictionary (vthe entries ( ( ))( ( ))( - ( ))(phv )that isan entry ( ( , )of dictionary (vhas key and value ( note that the last entry stores the special key with the realization of the multi-way search tree aboveprocessing -node while searching for an entry of with key can be done by performing search operation to find the entry ( ,( , )in (vwith smallest key greater than or equal to we distinguish two casesif then we continue the search by processing child (note that if the special key is returnedthen is greater than all the keys stored at node vand we continue the search processing child otherwise ( = )then the search terminates successfully consider the space requirement for the above realization of multi-way search tree storing entries by proposition using any of the common realizations of ordered dictionaries (for the secondary structures of the nodes of tthe overall space requirement for is (nconsider next the time spent answering search in the time spent at -node of during search depends on how we realize the secondary data structure (vif (vis realized with sorted array (that isan ordered search table)then we can process in (logdtime if instead (vis realized using an unsorted list insteadthen processing takes (dtime let dmax denote the maximum number of children of any node of tand let denote the height of the search time in multi-way search tree is either (hd max or (hlogd max )depending on the specific implementation of the secondary structures at the nodes of (the dictionaries ( )if max is constantthe running time for performing search is ( )irrespective of the implementation of the secondary structures thusthe primary efficiency goal for multi-way search tree is to keep the height as small as possiblethat iswe want to be logarithmic function of nthe total number of entries stored in the dictionary search tree with logarithmic heightsuch as thisis called balanced search tree we discuss balanced search tree that caps max at next definition of ( , tree
21,252
node small and also keeps the primary multi-way tree balanced is the ( , treewhich is sometimes called - tree or tree this data structure achieves these goals by maintaining two simple properties (see figure )size propertyevery internal node has at most four children depth propertyall the external nodes have the same depth figure ( , tree againwe assume that external nodes are empty andfor the sake of simplicitywe describe our search and update methods assuming that external nodes are real nodesalthough this latter requirement is not strictly needed enforcing the size property for ( , trees keeps the nodes in the multi-way search tree simple it also gives rise to the alternative name tree,since it implies that each internal node in the tree has or children another implication of this rule is that we can represent the dictionary (vstored at each internal node using an unordered list or an ordered arrayand still achieve ( )-time performance for all operations (since max the depth propertyon the other handenforces an important bound on the height of ( , tree proposition the height of ( , tree storing entries is (log njustificationlet be the height of ( , tree storing entries we justify the proposition by showing that the claims / log( + )<= ( and
21,253
( are true to justify these claims note first thatby the size propertywe can have at most nodes at depth at most nodes at depth and so on thusthe number of external nodes in is at most likewiseby the depth property and the definition of ( , treewe must have at least nodes at depth at least nodes at depth and so on thusthe number of external nodes in is at least in additionby proposition the number of external nodes in is thereforewe obtain <= + and + <= taking the logarithm in base of each of the above termswe get that <=log( + and log( + <= hwhich justifies our claims ( and proposition states that the size and depth properties are sufficient for keeping multi-way tree balanced (section moreoverthis proposition implies that performing search in ( , tree takes (logntime and that the specific realization of the secondary structures at the nodes is not crucial design choicesince the maximum number of children max is constant ( we canfor exampleuse simple ordered dictionary implementationsuch as an array-list search tablefor each secondary structure update operations for ( , trees maintaining the size and depth properties requires some effort after performing insertions and removals in ( , treehowever we discuss these operations next insertion to insert new entry ( , )with key kinto ( , tree twe first perform search for assuming that has no entry with key kthis search terminates
21,254
entry into node and add new child (an external nodeto on the left of that iswe add entry (kxwto the dictionary (vour insertion method preserves the depth propertysince we add new external node at the same level as existing external nodes neverthelessit may violate the size property indeedif node was previously -nodethen it may become -node after the insertionwhich causes the tree to no longer be ( , tree this type of violation of the size property is called an overflow at node vand it must be resolved in order to restore the properties of ( , tree let , be the children of vand let be the keys stored at to remedy the overflow at node vwe perform split operation on as follows (see figure )replace with two nodes and ''where is -node with children storing keys and 'is -node with children , storing key if was the root of tcreate new root node uelselet be the parent of insert key into and make and 'children of uso that if was child of uthen and 'become children and of urespectively we show sequence of insertions in ( , tree in figure figure node split(aoverflow at -node (bthe third key of inserted into the parent of (cnode replaced with -node and -node 'figure sequence of insertions into ( , tree(ainitial tree with one entry(binsertion of (cinsertion of (dinsertion of which causes an overflow(esplitwhich causes the creation of new root node(fafter the split(ginsertion of (
21,255
after the split(kinsertion of (linsertion of
21,256
21,257
stored at such nodes thusit can be implemented to run in ( time as consequence of split operation on node va new overflow may occur at the parent of if such an overflow occursit triggers in turn split at node (see figure split operation either eliminates the overflow or propagates it into the parent of the current node hencethe number of split operations is bounded by the height of the treewhich is (lognby proposition thereforethe total time to perform an insertion in ( , tree is (lognfigure an insertion in ( , tree that causes cascading split(abefore the insertion(binsertion of causing an overflow(ca split(dafter the split new overflow occurs(eanother splitcreating new root node(ffinal tree removal
21,258
begin such an operation by performing search in for an entry with key removing such an entry from ( , tree can always be reduced to the case where the entry to be removed is stored at node whose children are external nodes supposefor instancethat the entry with key that we wish to remove is stored in the ith entry ( , at node that has only internal-node children in this casewe swap the entry ( , with an appropriate entry that is stored at node with external-node children as follows (see figure ) we find the right-most internal node in the subtree rooted at the ith child of znoting that the children of node are all external nodes we swap the entry ( at with the last entry of once we ensure that the entry to remove is stored at node with only externalnode children (because either it was already at or we swapped it into )we simply remove the entry from (that isfrom the dictionary ( )and remove the ith external node of removing an entry (and childfrom node as described above preserves the depth propertyfor we always remove an external node child from node with only external-node children howeverin removing such an external node we may violate the size property at indeedif was previously -nodethen it becomes -node with no entries after the removal (figure and )which is not allowed in ( , tree this type of violation of the size property is called an underflow at node to remedy an underflowwe check whether an immediate sibling of is -node or -node if we find such sibling wthen we perform transfer operationin which we move child of to va key of to the parent of and wand key of to (see figure and if has only one siblingor if both immediate siblings of are -nodesthen we perform fusion operationin which we merge with siblingcreating new node 'and move key from the parent of to (see figure and fusion operation at node may cause new underflow to occur at the parent of vwhich in turn triggers transfer or fusion at (see figure hencethe number of fusion operations is bounded by the height of the treewhich is (lognby proposition if an underflow propagates all the way up to the rootthen the root is simply deleted (see figure and we show sequence of removals from ( , tree in figures and figure sequence of removals from ( , tree(aremoval of causing an underflow(ba transfer operation(cafter the transfer operation(dremoval of causing an underflow(ea fusion
21,259
(hafter removing
21,260
propagating sequence of fusions in ( , tree(aremoval of which causes an underflow(bfusionwhich causes another underflow(csecond fusion operationwhich causes the root to be removed(dfinal tree performance of ( , trees table summarizes the running times of the main operations of dictionary realized with ( , tree the time complexity analysis is based on the followingthe height of ( , tree storing entries is (logn)by proposition splittransferor fusion operation takes ( time searchinsertionor removal of an entry visits (lognnodes table performance of an -entry dictionary realized by ( , treewhere denotes the size of the
21,261
(noperation time sizeisempty ( findinsertremove (lognfindall (logn sthus( , trees provide for fast dictionary search and update operations ( , trees also have an interesting relationship to the data structure we discuss next red-black trees although avl trees and ( , trees have number of nice propertiesthere are some dictionary applications for which they are not well suited for instanceavl trees may require many restructure operations (rotationsto be performed after removaland ( , trees may require many fusing or split operations to be performed after either an insertion or removal the data structure we discuss in this sectionthe redblack treedoes not have these drawbackshoweveras it requires that only ( structural changes be made after an update in order to stay balanced red-black tree is binary search tree (see section with nodes colored red and black in way that satisfies the following propertiesroot propertythe root is black external propertyevery external node is black internal propertythe children of red node are black depth propertyall the external nodes have the same black depthdefined as the number of black ancestors minus one (recall that node is an ancestor of itself an example of red-black tree is shown in figure
21,262
tree of figure each external node of this red-black tree has black ancestors (including itself)henceit has black depth we use the color blue instead of red alsowe use the convention of giving an edge of the tree the same color as the child node as for previous types of search treeswe assume that entries are stored at the internal nodes of red-black treewith the external nodes being empty placeholders alsowe assume that the external nodes are actual nodesbut we note thatat the expense of slightly more complicated methodsexternal nodes could be null we can make the red-black tree definition more intuitive by noting an interesting correspondence between red-black trees and ( , treesas illustrated in figure namelygiven red-black treewe can construct corresponding ( , tree by merging every red node into its parent and storing the entry from at its parent converselywe can transform any ( , tree into corresponding red-black tree by coloring each node black and performing the following transformation for each internal node vif is -nodethen keep the (blackchildren of as is if is -nodethen create new red node wgive ' first two (blackchildren to wand make and ' third child be the two children of if is -nodethen create two new red nodes and zgive ' first two (blackchildren to wgive ' last two (blackchildren to zand make and be the two children of
21,263
and red-black tree( -node( -node( -node the correspondence between ( , trees and red-black trees provides important intuition that we will use in our discussion of how to perform updates in red-black trees in factthe update algorithms for red-black trees are mysteriously complex without this intuition proposition the height of red-black tree storing entries is (lognjustificationlet be red-black tree storing entriesand let be the height of we justify this proposition by establishing the following factlog( < < log( let be the common black depth of all the external nodes of let be the ( , tree associated with tand let be the height of because of the correspondence between red-black trees and ( , treeswe know that henceby proposition <log( by the internal node propertyh < thuswe obtain <
21,264
the fact that has internal nodes we assume that red-black tree is realized with linked structure for binary trees (section )in which we store dictionary entry and color indicator at each node thus the space requirement for storing keys is (nthe algorithm for searching in red-black tree is the same as that for standard binary search tree (section thussearching in red-black tree takes (logntime update operations performing the update operations in red-black tree is similar to that of binary search treeexcept that we must additionally restore the color properties insertion now consider the insertion of an entry with key into red-black tree tkeeping in mind the correspondence between and its associated ( , tree and the insertion algorithm for the algorithm initially proceeds as in binary search tree (section namelywe search for in until we reach an external node of tand we replace this node with an internal node zstoring ( ,xand having two external-node children if is the root of twe color blackelse we color red we also color the children of black this action corresponds to inserting ( ,xinto node of the ( , tree with external children in additionthis action preserves the rootexternal and depth properties of tbut it may violate the internal property indeedif is not the root of and the parent of is redthen we have parent and child (namelyv and zthat are both red note that by the root propertyv cannot be the root of tand by the internal property (which was previously satisfied)the parent of must be black since and its parent are redbut ' grandparent is blackwe call this violation of the internal property double red at node to remedy double redwe consider two cases case the sibling of is black (see figure in this casethe double red denotes the fact that we have created in our red-black tree malformed replacement for corresponding -node of the ( , tree which has as its children the four black children of uvand our malformed replacement has one red node (vthat is the parent of another red node ( )while we want it to have the two red nodes as siblings instead to fix this problemwe perform trinode restructuring of the trinode restructuring is done by the operation restructure( )which consists of the following steps (see again figure this operation is also discussed in section )
21,265
take node zits parent vand grandparent uand temporarily relabel them as aband cin left-to-right orderso that aband will be visited in this order by an inorder tree traversal replace the grandparent with the node labeled band make nodes and the children of bkeeping inorder relationships unchanged after performing the restructure(zoperationwe color black and we color and red thusthe restructuring eliminates the double red problem figure restructuring red-black tree to remedy double red(athe four configurations for uvand before restructuring(bafter restructuring case the sibling of is red (see figure in this casethe double red denotes an overflow in the corresponding ( , tree to fix the problemwe
21,266
and black and their parent red (unless is the rootin which caseit is colored blackit is possible thatafter such recoloringthe double red problem reappearsalbeit higher up in the tree tsince may have red parent if the double red problem reappears at uthen we repeat the consideration of the two cases at thusa recoloring either eliminates the double red problem at node zor propagates it to the grandparent of we continue going up performing recolorings until we finally resolve the double red problem (with either final recoloring or trinode restructuringthusthe number of recolorings caused by an insertion is no more than half the height of tree tthat isno more than log( by proposition figure recoloring to remedy the double red problem(abefore recoloring and the corresponding -node in the associated ( , tree before the split(bafter the recoloring (and corresponding nodes in the associated ( , tree after the split
21,267
tree figure sequence of insertions in redblack tree(ainitial tree(binsertion of (cinsertion of which causes double red(dafter restructuring(einsertion of which causes double red(fafter recoloring (the root remains black)(ginsertion of (hinsertion of (iinsertion of which causes double red(jafter restructuring(kinsertion of which causes double red(lafter recoloring (continues in figure
21,268
sequence of insertions in redblack tree(minsertion of which causes double red(nafter restructuring(oinsertion of which causes double red(pafter recoloring there is again double redto be handled by restructuring(qafter restructuring (continued from figure
21,269
since the case action eliminates the double-red problem with single trinode restructuring and the case action performs no restructuring operationsat most one restructuring is needed in red-black tree insertion by the above analysis and the fact that restructuring or recoloring takes ( timewe have the followingproposition the insertion of key-value entry in red-black tree storing entries can be done in (logntime and requires (lognrecolorings and one trinode restructuring ( restructure operation
21,270
suppose now that we are asked to remove an entry with key from red-black tree removing such an entry initially proceeds as for binary search tree (section firstwe search for node storing such an entry if node does not have an external childwe find the internal node following in the inorder traversal of tmove the entry at to uand perform the removal at thuswe may consider only the removal of an entry with key stored at node with an external child alsoas we did for insertionswe keep in mind the correspondence between red-black tree and its associated ( , tree (and the removal algorithm for 'to remove the entry with key from node of with an external child we proceed as follows let be the sibling of and be the parent of we remove nodes and wand make child of if was red (hence is blackor is red (hence was black)we color black and we are done ifinsteadr is black and was blackthento preserve the depth propertywe give fictitious double black color we now have color violationcalled the double black problem double black in denotes an underflow in the corresponding ( , tree recall that is the parent of the double black node to remedy the double-black problem at rwe consider three cases case the sibling of is black and has red child (see figure resolving this case corresponds to transfer operation in the ( , tree we perform trinode restructuring by means of operation restructure(zrecall that the operation restructure(ztakes the node zits parent yand grandparent xlabels them temporarily left to right as aband cand replaces with the node labeled bmaking it the parent of the other two (see also the description of restructure in section we color and blackgive the former color of xand color black this trinode restructuring eliminates the double black problem henceat most one restructuring is performed in removal operation in this case figure restructuring of red-black tree to remedy the double black problem(aand (bconfigurations before the restructuringwhere is right child and the associated nodes in the corresponding ( , tree before the transfer (two other symmetric configurations where is left child are possible)(cconfiguration after the restructuring and the associated nodes in the corresponding ( , tree after the transfer the grey color for node in parts (
21,271
this node may be colored either red or black
21,272
figures and resolving this case corresponds to fusion operation in the corresponding ( , tree we do recoloringwe color blackwe color redandif is redwe color it black (figure )otherwisewe color double black (figure henceafter this recoloringthe double black problem may reappear at the parent of (see figure that isthis recoloring either eliminates the double black problem or propagates it into the parent of the current node we then repeat consideration of these three cases at the parent thussince case performs trinode restructuring operation and stops (andas we will soon seecase is similar)the number of recolorings caused by removal is no more than log( figure recoloring of red-black tree that fixes the double black problem(abefore the recoloring and corresponding nodes in the associated ( , tree before the fusion (other similar configurations are possible)(bafter the recoloring and corresponding nodes in the associated ( , tree after the fusion
21,273
recoloring of red-black tree that propagates the double black problem(aconfiguration before the recoloring and corresponding nodes in the associated ( , tree before the fusion (other similar configurations are possible)(bconfiguration after the recoloring and corresponding nodes in the associated ( , tree after the fusion
21,274
adjustment operationas follows if is the right child of xlet be the right child of yotherwiselet be the left child of execute the trinode restructuring operation restructure( )which makes the parent of color black and red an adjustment corresponds to choosing different representation of -node in the ( , tree after the adjustment operationthe sibling of is blackand either case or case applieswith different meaning of and note that if case appliesthe double-black problem cannot reappear thusto complete case we make one more application of either case or case above and we are done thereforeat most one adjustment is performed in removal operation figure adjustment of red-black tree in the presence of double black problem(
21,275
corresponding nodes in the associated ( , tree ( symmetric configuration is possible)(bconfiguration after the adjustment with the same corresponding nodes in the associated ( , tree from the above algorithm descriptionwe see that the tree updating needed after removal involves an upward march in the tree twhile performing at most
21,276
thussince any changes we make at node in during this upward march takes ( time (because it affects constant number of nodes)we have the followingproposition the algorithm for removing an entry from red-black tree with entries takes (logntime and performs (lognrecolorings and at most one adjustment plus one additional trinode restructuring thusit performs at most two restructure operations in figures and we show sequence of removal operations on redblack tree we illustrate case restructurings in figure and we illustrate case recolorings at several places in figures and finallyin figure and jwe show an example of case adjustment figure sequence of removals from redblack tree(ainitial tree(bremoval of (cremoval of causing double black (handled by restructuring)(dafter restructuring (continues in figure figure sequence of removals in redblack tree (continued)(eremoval of (fremoval of
21,277
after recoloring(hremoval of (iremoval of causing double black (handled by an adjustment)(jafter the adjustment the double black needs to be handled by recoloring(kafter the recoloring (continued from figure
21,278
table summarizes the running times of the main operations of dictionary realized by means of red-black tree we illustrate the justification for these bounds in figure
21,279
realized by red-black treewhere denotes the size of the collection returned by findall the space usage is (noperation time sizeisempty ( findinsertremove (lognfindall (logn +sfigure illustrating the running time of searches and updates in red-black tree the time performance is ( per levelbroken into down phasewhich typically involves searchingand an up phasewhich typically involves recolorings and performing local trinode restructurings (rotations
21,280
searching and updating in dictionary the red-black tree data structure is slightly more complicated than its corresponding ( , tree even soa red-black tree has conceptual advantage that only constant number of trinode restructurings are ever needed to restore the balance in red-black tree after an update java implementation in code fragments through we show the major portions of java implementation of dictionary realized by means of red-black tree the main class includes nested classrbnodeshown in code fragment which extends the btnode class used to represent key-value entry of binary search tree it defines an additional instance variable isredrepresenting the color of the nodeand methods to set and return it code fragment instance variablesnested classand constructor for rbtree
21,281
binarysearchtree (code fragments through we assume the parent class supports the method restructure for performing trinode restructurings (rotations)its implementation is left as an exercise ( - class rbtree inherits methods sizeisemptyfindand findall from binarysearchtree but overrides methods insert and remove it implements these two operations by first calling the corresponding method of the parent class and then remedying any color violations that this update may have caused several auxiliary methods of class rbtree are not shownbut their names suggest their meanings and their implementations are straightforward code fragment the dictionary adt method insert and auxiliary methods createnode and remedydoublered of class rbtree
21,282
corresponding methods of the superclass first and then rebalance the tree by calling
21,283
(given by the actionpos variable inherited from the superclassto the root code fragment method remove and auxiliary method remedydoubleblack of class rbtree
21,284
exercises for source code and help with exercisesplease visit java datastructures net reinforcement - we defined binary search tree so that keys equal to node' key can be in either the left or right subtree of that node suppose we change the definition so that we restrict equal keys to the right subtree what must subtree of binary search tree containing only equal keys look like in this caser- how many different binary search trees can store the keys { , , } - how many different binary search trees can store the keys { , , , } - insertinto an empty binary search treeentries with keys (in this orderdraw the tree after each insertion - suppose that the methods of binarysearchtree (code fragments are used to perform the updates shown in figures and what is the node referenced by action pos after each updater- dr amongus claims that the order in which fixed set of entries is inserted into binary search tree does not matter--the same tree results every time give small example that proves he is wrong - dr amongus claims that the order in which fixed set of entries is inserted into an avl tree does not matter--the same avl tree results every time give small example that proves he is wrong -
21,285
- draw the avl tree resulting from the insertion of an entry with key into the avl tree of figure - draw the avl tree resulting from the removal of the entry with key from the avl tree of figure - explain why performing rotation in an -node binary tree represented using an array list takes ohm(ntime - is the search tree of figure ( , treewhy or why notr- an alternative way of performing split at node in ( , tree is to partition into and ''with being -node and ' -node which of the keys or do we store at ' parent in this casewhyr- dr amongus claims that ( , tree storing set of entries will always have the same structureregardless of the order in which the entries are inserted show that he is wrong - draw four different red-black trees that correspond to the same ( , tree - consider the set of keys { , , , , , , , , , , , , , , draw ( , tree storing as its keys using the fewest number of nodes draw ( , tree storing as its keys using the maximum number of nodes
21,286
consider the sequence of keys ( , , , , , , , , , , draw the result of inserting entries with these keys (in the given orderinto an initially empty ( , tree an initially empty red-black tree - for the following statements about red-black treesprovide justification for each true statement and counterexample for each false one subtree of red-black tree is itself red-black tree the sibling of an external node is either external or it is red there is unique ( , tree associated with given red-black tree there is unique red-black tree associated with given ( , tree - draw an example red-black tree that is not an avl tree - consider tree storing , entries what is the worst-case height of in the following casesa is an avl tree
21,287
is red-black tree is splay tree is binary search tree - perform the following sequence of operations in an initially empty splay tree and draw the tree after each set of operations insert keys in this order search for keys in this order delete keys in this order - what does splay tree look like if its entries are accessed in increasing order by their keysr- explain how to use an avl tree or red-black tree to sort comparable elements in (nlogntime in the worst case - can we use splay tree to sort comparable elements in (nlogntime in the worst casewhy or why notcreativity
21,288
design variation of algorithm treesearch for performing the operation findal(kin an ordered dictionary implemented with binary search tree tand show that it runs in time ( )where is the height of and is the size of the collection returned - describe how to perform an operation removeall( )which removes all the entries whose keys equal in an ordered dictionary implemented with binary search tree tand show that this method runs in time ( )where is the height of and is the size of the iterator returned - draw schematic of an avl tree such that single remove operation could require ohm(logntrinode restructurings (or rotationsfrom leaf to the root in order to restore the height-balance property - show how to perform an operationremoveall( )which removes all entries with keys equal to kin dictionary implemented with an avl tree in time (slogn)where is the number of entries in the dictionary and is the size of the iterator returned - if we maintain reference to the position of the left-most internal node of an avl treethen operation first (section can be performed in ( time describe how the implementation of the other dictionary methods needs to be modified to maintain reference to the left-most position - show that any -node binary tree can be converted to any other -node binary tree using (nrotations - let be an ordered dictionary with entries implemented by means of an avl tree show how to implement the following operation on in time (logn )where is the size of the iterator returnedfindallinrange( , )return an iterator of all the entries in with key such that < <
21,289
let be an ordered dictionary with entries show how to modify the avl tree to implement the following method for in time (logn)countallinrange( , )compute and return the number of entries in with key such that < < - show that the nodes that become unbalanced in an avl tree after operation insertatexternal is performedwithin the execution of an insert operationmay be nonconsecutive on the path from the newly inserted node to the root - show that at most one node in an avl tree becomes unbalanced after operation removeexternal is performed within the execution of remove dictionary operation - show that at most one trinode restructuring operation is needed to restore balance after any insertion in an avl tree - let and be ( , trees storing and entriesrespectivelysuch that all the entries in have keys less than the keys of all the entries in describe an (logn logmtime method for joining tand into single tree that stores all the entries in and - repeat the previous problem for red-black trees and - justify proposition - the boolean indicator used to mark nodes in red-black tree as being "redor "blackis not strictly needed when we have distinct keys describe scheme for implementing red-black tree without adding any extra space to standard binary search tree nodes how does your scheme affect the search and update times
21,290
let be red-black tree storing entriesand let be the key of an entry in show how to construct from tin (logntimetwo red-black trees and ''such that contains all the keys of less than kand 'contains all the keys of greater than this operation destroys - show that the nodes of any avl tree can be colored "redand "blackso that becomes red-black tree - the mergeable heap adt consists of operations insert( , )removemin()unionwith( )and min()where the unionwith(hoperation performs union of the mergeable heap with the present onedestroying the old versions of both describe concrete implementation of the mergeable heap adt that achieves (lognperformance for all its operations - consider variation of splay treescalled half-splay treeswhere splaying node at depth stops as soon as the node reaches depth [ / perform an amortized analysis of half-splay trees - the standard splaying step requires two passesone downward pass to find the node to splayfollowed by an upward pass to splay the node describe method for splaying and searching for in one downward pass each substep now requires that you consider the next two nodes in the path down to xwith possible zig substep performed at the end describe how to perform the zig-zigzig-zagand zig steps - describe sequence of accesses to an -node splay tree twhere is oddthat results in consisting of single chain of internal nodes with external node childrensuch that the internal-node path down alternates between left children and right children - explain how to implement an array list of elements so that the methods add and get take (logntime in the worst case (with no need for an expandable array
21,291
- -body simulations are an important modeling tool in physicsastronomyand chemistry in this projectyou are to write program that performs simple nbody simulation called "jumping leprechauns this simulation involves leprechaunsnumbered to it maintains gold value for each leprechaun iwhich begins with each leprechaun starting out with million dollars worth of goldthat isg for eachi , , in additionthe simulation also maintainsfor each leprechaun ia place on the horizonwhich is represented as double-precision floating point numberx in each iteration of the simulationthe simulation processes the leprechauns in order processing leprechaun during this iteration begins by computing new place on the horizon for iwhich is determined by the assignment - rg where is random floating-point number between - and leprechaun then steals half the gold from the nearest leprechauns on either side of him and adds this gold to his gold valueg write program that can perform series of iterations in this simulation for given numbernof leprechauns try to include visualization of the leprechauns in this simulationincluding their gold values and horizon positions you must maintain the set of horizon positions using an ordered dictionary data structure described in this - extend class binarysearchtree (code fragments to support the methods of the ordered dictionary adt (see section - implement class restructurablenodebinarytree that supports the methods of the binary tree adtplus method restructure for performing rotation operation this class is component of the implementation of an avl tree given in section - write java class that implements all the methods of the ordered dictionary adt (see section using an avl tree - write java class that implements all the methods of the ordered dictionary adt (see section using ( , tree
21,292
write java class that implements all the methods of the ordered dictionary adt (see section using red-black tree - form three-programmer team and have each member implement different one of the previous three projects perform extensive experimental studies to compare the speed of these three implementations design three sets of experimentseach favoring different implementation - write java class that can take any red-black tree and convert it into its corresponding ( , tree and can take any ( , tree and convert it into its corresponding red-black tree - perform an experimental study to compare the performance of red-black tree with that of skip list - prepare an implementation of splay trees that uses bottom-up splaying as described in this and another that uses top-down splaying as described in exercise - perform extensive experimental studies to see which implementation is better in practiceif any notes some of the data structures discussed in this are extensively covered by knuth in his sorting and searching book [ ]and by mehlhorn in [ avl trees are due to adel'son-vel'skii and landis [ ]who invented this class of balanced search trees in binary search treesavl treesand hashing are described in knuth' sorting and searching [ book average-height analyses for binary search trees can be found in the books by ahohopcroftand ullman [ and cormenleisersonand rivest [ the handbook by gonnet and baeza-yates [ contains number of theoretical and experimental comparisons among dictionary implementations ahohopcroftand ullman [ discuss ( , treeswhich are similar to ( , trees red-black trees were defined by bayer [ variations and interesting properties of red-black trees are presented in paper by guibas and sedgewick [ the reader interested in learning more about different balanced tree data structures is referred to the books by mehlhorn [ and tarjan [ ]and the book by mehlhorn and tsakalidis [ knuth [ is excellent additional reading that includes
21,293
[ (see also [ ] sortingsetsand selection contents merge-sort divide-and-conquer merging arrays and lists the running time of merge-sort java implementations of merge-sort
21,294
merge-sort and recurrence equations quick-sort randomized quick-sort in-place quick-sort lower bound on sorting bucket-sort and radix-sort bucket-sort radix-sort
21,295
comparison of sorting algorithms the set adt and union/find structures simple set implementation partitions with union-find operations tree-based partition implementation selection prune-and-search randomized quick-select
21,296
exercises java datastructures net merge-sort in this sectionwe present sorting techniquecalled merge-sortwhich can be described in simple and compact way using recursion divide-and-conquer merge-sort is based on an algorithmic design pattern called divide-and-conquer the divide-and-conquer pattern consists of the following three steps divideif the input size is smaller than certain threshold (sayone or two elements)solve the problem directly using straightforward method and return the solution so obtained otherwisedivide the input data into two or more disjoint subsets recurrecursively solve the subproblems associated with the subsets conquertake the solutions to the subproblems and "mergethem into solution to the original problem using divide-and-conquer for sorting recall that in sorting problem we are given sequence of objectsstored in linked list or an arraytogether with some comparator defining total order on these objectsand we are asked to produce an ordered representation of these objects to allow for sorting of either representationwe will describe our sorting algorithm at high level for sequences and explain the details needed to implement it for linked lists and arrays to sort sequence with elements using the three divide-and-conquer stepsthe merge-sort algorithm proceeds as follows divide:if has zero or one elementreturn immediatelyit is already sorted otherwise ( has at least two elements)remove all the elements from and put them into two sequencess and each containing about half of the
21,297
the remaining / elements / elements of sand contains recurrecursively sort sequences and conquerput back the elements into by merging the sorted sequences and into sorted sequence in reference to the divide stepwe recall that the notation indicates the ceiling of xthat isthe smallest integer msuch that < similarlythe notation indicates the floor of xthat isthe largest integer ksuch that < we can visualize an execution of the merge-sort algorithm by means of binary tree tcalled the merge-sort tree each node of represents recursive invocation (or callof the merge-sort algorithm we associate with each node of the sequence that is processed by the invocation associated with the children of node are associated with the recursive calls that process the subsequences and of the external nodes of are associated with individual elements of scorresponding to instances of the algorithm that make no recursive calls figure summarizes an execution of the merge-sort algorithm by showing the input and output sequences processed at each node of the merge-sort tree the step-by-step evolution of the merge-sort tree is shown in figures through this algorithm visualization in terms of the merge-sort tree helps us analyze the running time of the merge-sort algorithm in particularsince the size of the input sequence roughly halves at each recursive call of merge-sortthe height of the merge-sort tree is about log (recall that the base of log is if omittedfigure merge-sort tree for an execution of the merge-sort algorithm on sequence with elements(ainput sequences processed at each node of (boutput sequences generated at each node of
21,298
of merge-sort the nodes drawn with dashed lines represent calls that have not been made yet the node drawn with thick lines represents the current call the empty nodes drawn with thin lines represent completed calls the remaining nodes (drawn with thin lines and not emptyrepresent calls that are waiting
21,299
figure visualization of an execution of mergesort (continues in figure