id
int64
0
25.6k
text
stringlengths
0
4.59k
13,000
def first(self)"""return (but do not removethe element at the front of the queue raise empty exception if the queue is empty ""if self is empty)raise emptyqueue is empty head self tail next return head element def dequeue(self)"""remove and return the first element of the queue ( fiforaise empty exception if the queue is empty ""if self is empty)raise emptyqueue is empty oldhead self tail next removing only element if self size = queue becomes empty self tail none elsebypass the old head self tail next oldhead next self size - return oldhead element def enqueue(selfe)"""add an element to the back of queue ""node will be new tail node newest self node(enoneif self is empty)initialize circularly newest next newest elsenew node points to head newest next self tail next old tail points to new node self tail next newest new node becomes the tail self tail newest self size + def rotate(self)"""rotate front element to the back of the queue ""if self size self tail self tail next old head becomes new tail code fragment implementation of circularqueue classusing circularly linked list as storage (continued from code fragment
13,001
doubly linked lists in singly linked listeach node maintains reference to the node that is immediately after it we have demonstrated the usefulness of such representation when managing sequence of elements howeverthere are limitations that stem from the asymmetry of singly linked list in the opening of section we emphasized that we can efficiently insert node at either end of singly linked listand can delete node at the head of listbut we are unable to efficiently delete node at the tail of the list more generallywe cannot efficiently delete an arbitrary node from an interior position of the list if only given reference to that nodebecause we cannot determine the node that immediately precedes the node to be deleted (yetthat node needs to have its next reference updatedto provide greater symmetrywe define linked list in which each node keeps an explicit reference to the node before it and reference to the node after it such structure is known as doubly linked list these lists allow greater variety of ( )-time update operationsincluding insertions and deletions at arbitrary positions within the list we continue to use the term "nextfor the reference to the node that follows anotherand we introduce the term "prevfor the reference to the node that precedes it header and trailer sentinels in order to avoid some special cases when operating near the boundaries of doubly linked listit helps to add special nodes at both ends of the lista header node at the beginning of the listand trailer node at the end of the list these "dummynodes are known as sentinels (or guards)and they do not store elements of the primary sequence doubly linked list with such sentinels is shown in figure header next next jfk prev next pvd prev next trailer sfo prev prev figure doubly linked list representing the sequence jfkpvdsfo }using sentinels header and trailer to demarcate the ends of the list when using sentinel nodesan empty list is initialized so that the next field of the header points to the trailerand the prev field of the trailer points to the headerthe remaining fields of the sentinels are irrelevant (presumably nonein pythonfor nonempty listthe header' next will refer to node containing the first real element of sequencejust as the trailer' prev references the node containing the last element of sequence
13,002
advantage of using sentinels although we could implement doubly linked list without sentinel nodes (as we did with our singly linked list in section )the slight extra space devoted to the sentinels greatly simplifies the logic of our operations most notablythe header and trailer nodes never change--only the nodes between them change furthermorewe can treat all insertions in unified mannerbecause new node will always be placed between pair of existing nodes in similar fashionevery element that is to be deleted is guaranteed to be stored in node that has neighbors on each side for contrastlook back at our linkedqueue implementation from section its enqueue methodgiven in code fragment adds new node to the end of the list howeverits implementation required conditional to manage the special case of inserting into an empty list in the general casethe new node was linked after the existing tail but when adding to an empty listthere is no existing tailinstead it is necessary to reassign self head to reference the new node the use of sentinel node in that implementation would eliminate the special caseas there would always be an existing node (possibly the headerbefore new node inserting and deleting with doubly linked list every insertion into our doubly linked list representation will take place between pair of existing nodesas diagrammed in figure for examplewhen new element is inserted at the front of the sequencewe will simply add the new node between the header and the node that is currently after the header (see figure header trailer bwi jfk sfo (aheader trailer bwi jfk pvd sfo pvd sfo (bheader trailer bwi jfk (cfigure adding an element to doubly linked list with header and trailer sentinels(abefore the operation(bafter creating the new node(cafter linking the neighbors to the new node
13,003
header trailer bwi jfk sfo (aheader trailer pvd bwi jfk sfo (bheader trailer pvd bwi jfk sfo (cfigure adding an element to the front of sequence represented by doubly linked list with header and trailer sentinels(abefore the operation(bafter creating the new node(cafter linking the neighbors to the new node the deletion of nodeportrayed in figure proceeds in the opposite fashion of an insertion the two neighbors of the node to be deleted are linked directly to each otherthereby bypassing the original node as resultthat node will no longer be considered part of the list and it can be reclaimed by the system because of our use of sentinelsthe same implementation can be used when deleting the first or the last element of sequencebecause even such an element will be stored at node that lies between two others header trailer bwi jfk pvd sfo (aheader trailer bwi jfk pvd sfo (bheader trailer bwi jfk sfo (cfigure removing the element pvd from doubly linked list(abefore the removal(bafter linking out the old node(cafter the removal (and garbage collection
13,004
basic implementation of doubly linked list we begin by providing preliminary implementation of doubly linked listin the form of class named doublylinkedbase we intentionally name the class with leading underscore because we do not intend for it to provide coherent public interface for general use we will see that linked lists can support general insertions and deletions in ( worst-case timebut only if the location of an operation can be succinctly identified with array-based sequencesan integer index was convenient means for describing position within sequence howeveran index is not convenient for linked lists as there is no efficient way to find the jth elementit would seem to require traversal of portion of the list when working with linked listthe most direct way to describe the location of an operation is by identifying relevant node of the list howeverwe prefer to encapsulate the inner workings of our data structure to avoid having users directly access nodes of list in the remainder of this we will develop two public classes that inherit from our doublylinkedbase class to provide more coherent abstractions specificallyin section we provide linkeddeque class that implements the double-ended queue adt introduced in section that class only supports operations at the ends of the queueso there is no need for user to identify an interior position within the list in section we introduce new positionallist abstraction that provides public interface that allows arbitrary insertions and deletions from list our low-level doublylinkedbase class relies on the use of nonpublic node class that is similar to that for singly linked listas given in code fragment except that the doubly linked version includes prev attributein addition to the next and element attributesas shown in code fragment class node"""lightweightnonpublic class for storing doubly linked node ""slots _element _prev _next streamline memory def init (selfelementprevnext)self element element self prev prev self next next initialize node' fields user' element previous node reference next node reference code fragment python node class for use in doubly linked list the remainder of our doublylinkedbase class is given in code fragment the constructor instantiates the two sentinel nodes and links them directly to each other we maintain size member and provide public support for len and is empty so that these behaviors can be directly inherited by the subclasses
13,005
linked lists class doublylinkedbase """ base class providing doubly linked list representation "" class node """lightweightnonpublic class for storing doubly linked node "" (omitted heresee previous code fragment def init (self) """create an empty list "" self header self node(nonenonenone self trailer self node(nonenonenonetrailer is after header self header next self trailer header is before trailer self trailer prev self header self size number of elements def len (self) """return the number of elements in the list "" return self size def is empty(self) """return true if list is empty "" return self size = def insert between(selfepredecessorsuccessor) """add element between two existing nodes and return new node "" newest self node(epredecessorsuccessorlinked to neighbors predecessor next newest successor prev newest self size + return newest def delete node(selfnode) """delete nonsentinel node from the list and return its element "" predecessor node prev successor node next predecessor next successor successor prev predecessor self size - record deleted element element node element node prev node next node element none deprecate node return element return deleted element code fragment base class for managing doubly linked list
13,006
the other two methods of our class are the nonpublic utilitiesinsert between and delete node these provide generic support for insertions and deletionsrespectivelybut require one or more node references as parameters the implementation of the insert between method is modeled upon the algorithm that was previously portrayed in figure it creates new nodewith that node' fields initialized to link to the specified neighboring nodes then the fields of the neighboring nodes are updated to include the newest node in the list for later conveniencethe method returns reference to the newly created node the implementation of the delete node method is modeled upon the algorithm portrayed in figure the neighbors of the node to be deleted are linked directly to each otherthereby bypassing the deleted node from the list as formalitywe intentionally reset the prevnextand element fields of the deleted node to none (after recording the element to be returnedalthough the deleted node will be ignored by the rest of the listsetting its fields to none is advantageous as it may help python' garbage collectionsince unnecessary links to the other nodes and the stored element are eliminated we will also rely on this configuration to recognize node as "deprecatedwhen it is no longer part of the list implementing deque with doubly linked list the double-ended queue (dequeadt was introduced in section with an array-based implementationwe achieve all operations in amortized ( timedue to the occasional need to resize the array with an implementation based upon doubly linked listwe can achieve all deque operation in worst-case ( time we provide an implementation of linkeddeque class (code fragment that inherits from the doublylinkedbase class of the preceding section we do not provide an explicit init method for the linkeddeque classas the inherited version of that method suffices to initialize new instance we also rely on the inherited methods len and is empty in meeting the deque adt with the use of sentinelsthe key to our implementation is to remember that the header does not store the first element of the deque--it is the node just after the header that stores the first element (assuming the deque is nonemptysimilarlythe node just before the trailer stores the last element of the deque we use the inherited insert between method to insert at either end of the deque to insert an element at the front of the dequewe place it immediately between the header and the node just after the header an insertion at the end of deque is placed immediately before the trailer node note that these operations succeedeven when the deque is emptyin such situationthe new node is placed between the two sentinels when deleting an element from nonempty dequewe rely upon the inherited delete node methodknowing that the designated node is assured to have neighbors on each side
13,007
class linkeddequedoublylinkedbase)note the use of inheritance """double-ended queue implementation based on doubly linked list "" def first(self) """return (but do not removethe element at the front of the deque "" if self is empty) raise empty("deque is empty"real item just after header return self header next element def last(self) """return (but do not removethe element at the back of the deque "" if self is empty) raise empty("deque is empty" return self trailer prev element real item just before trailer def insert first(selfe) """add an element to the front of the deque "" self insert between(eself headerself header nextafter header def insert last(selfe) """add an element to the back of the deque ""before trailer self insert between(eself trailer prevself trailer def delete first(self) """remove and return the element from the front of the deque raise empty exception if the deque is empty "" if self is empty) raise empty("deque is empty"use inherited method return self delete node(self header next def delete last(self) """remove and return the element from the back of the deque raise empty exception if the deque is empty "" if self is empty) raise empty("deque is empty"use inherited method return self delete node(self trailer prevcode fragment implementation of linkeddeque class that inherits from the doublylinkedbase class
13,008
the positional list adt the abstract data types that we have considered thus farnamely stacksqueuesand double-ended queuesonly allow update operations that occur at one end of sequence or the other we wish to have more general abstraction for examplealthough we motivated the fifo semantics of queue as model for customers who are waiting to speak with customer service representativeor fans who are waiting in line to buy tickets to showthe queue adt is too limiting what if waiting customer decides to hang up before reaching the front of the customer service queueor what if someone who is waiting in line to buy tickets allows friend to "cutinto line at that positionwe would like to design an abstract data type that provides user way to refer to elements anywhere in sequenceand to perform arbitrary insertions and deletions when working with array-based sequences (such as python list)integer indices provide an excellent means for describing the location of an elementor the location at which an insertion or deletion should take place howevernumeric indices are not good choice for describing positions within linked list because we cannot efficiently access an entry knowing only its indexfinding an element at given index within linked list requires traversing the list incrementally from its beginning or endcounting elements as we go furthermoreindices are not good abstraction for describing local position in some applicationsbecause the index of an entry changes over time due to insertions or deletions that happen earlier in the sequence for exampleit may not be convenient to describe the location of person waiting in line by knowing precisely how far away that person is from the front of the line we prefer an abstractionas characterized in figure in which there is some other means for describing position we then wish to model situations such as when an identified person leaves the line before reaching the frontor in which new person is added to line immediately behind another identified person tickets me figure we wish to be able to identify the position of an element in sequence without the use of an integer index
13,009
as another examplea text document can be viewed as long sequence of characters word processor uses the abstraction of cursor to describe position within the document without explicit use of an integer indexallowing operations such as "delete the character at the cursoror "insert new character just after the cursor furthermorewe may be able to refer to an inherent position within documentsuch as the beginning of particular sectionwithout relying on character index (or even section numberthat may change as the document evolves node reference as positionone of the great benefits of linked list structure is that it is possible to perform ( )-time insertions and deletions at arbitrary positions of the listas long as we are given reference to relevant node of the list it is therefore very tempting to develop an adt in which node reference serves as the mechanism for describing position in factour doublylinkedbase class of section has methods insert between and delete node that accept node references as parameters howeversuch direct use of nodes would violate the object-oriented design principles of abstraction and encapsulation that were introduced in there are several reasons to prefer that we encapsulate the nodes of linked listfor both our sake and for the benefit of users of our abstraction it will be simpler for users of our data structure if they are not bothered with unnecessary details of our implementationsuch as low-level manipulation of nodesor our reliance on the use of sentinel nodes notice that to use the insert between method of our doublylinkedbase class to add node at the beginning of sequencethe header sentinel must be sent as parameter we can provide more robust data structure if we do not permit users to directly access or manipulate the nodes in that waywe ensure that users cannot invalidate the consistency of list by mismanaging the linking of nodes more subtle problem arises if user were allowed to call the insert between or delete node method of our doublylinkedbase classsending node that does not belong to the given list as parameter (go back and look at that code and see why it causes problem!by better encapsulating the internal details of our implementationwe have greater flexibility to redesign the data structure and improve its performance in factwith well-designed abstractionwe can provide notion of nonnumeric positioneven if using an array-based sequence for these reasonsinstead of relying directly on nodeswe introduce an independent position abstraction to denote the location of an element within listand then complete positional list adt that can encapsulate doubly linked list (or even an array-based sequencesee exercise -
13,010
the positional list abstract data type to provide for general abstraction of sequence of elements with the ability to identify the location of an elementwe define positional list adt as well as simpler position abstract data type to describe location within list position acts as marker or token within the broader positional list position is unaffected by changes elsewhere in listthe only way in which position becomes invalid is if an explicit command is issued to delete it position instance is simple objectsupporting only the following methodp element)return the element stored at position in the context of the positional list adtpositions serve as parameters to some methods and as return values from other methods in describing the behaviors of positional listwe being by presenting the accessor methods supported by list ll first)return the position of the first element of lor none if is empty last)return the position of the last element of lor none if is empty before( )return the position of immediately before position por none if is the first position after( )return the position of immediately after position por none if is the last position is empty)return true if list does not contain any elements len( )return the number of elements in the list iter( )return forward iterator for the elements of the list see section for discussion of iterators in python the positional list adt also includes the following update methodsl add first( )insert new element at the front of lreturning the position of the new element add last( )insert new element at the back of lreturning the position of the new element add before(pe)insert new element just before position in lreturning the position of the new element add after(pe)insert new element just after position in lreturning the position of the new element replace(pe)replace the element at position with element ereturning the element formerly at position delete( )remove and return the element at position in linvalidating the position for those methods of the adt that accept position as parameteran error occurs if is not valid position for list
13,011
note well that the firstand lastmethods of the positional list adt return the associated positionsnot the elements (this is in contrast to the corresponding first and last methods of the deque adt the first element of positional list can be determined by subsequently invoking the element method on that positionas firstelementthe advantage of receiving position as return value is that we can use that position to navigate the list for examplethe following code fragment prints all elements of positional list named data cursor data firstwhile cursor is not noneprint(cursor element)cursor data after(cursorprint the element stored at the position advance to the next position (if anythis code relies on the stated convention that the none object is returned when after is called upon the last position that return value is clearly distinguishable from any legitimate position the positional list adt similarly indicates that the none value is returned when the before method is invoked at the front of the listor when first or last methods are called upon an empty list thereforethe above code fragment works correctly even if the data list is empty because the adt includes support for python' iter functionusers may rely on the traditional for-loop syntax for such forward traversal of list named data for in dataprint(emore general navigational and update methods of the positional list adt are shown in the following example example the following table shows series of operations on an initially empty positional list to identify position instanceswe use variables such as and for ease of expositionwhen displaying the list contentswe use subscript notation to denote its positions operation add last( firstl add after( before(ql add before( elementl after(pl before(pl add first( delete( last) replace( return value none
13,012
doubly linked list implementation in this sectionwe present complete implementation of positionallist class using doubly linked list that satisfies the following important proposition proposition each method of the positional list adt runs in worst-case ( time when implemented with doubly linked list we rely on the doublylinkedbase class from section for our low-level representationthe primary responsibility of our new class is to provide public interface in accordance with the positional list adt we begin our class definition in code fragment with the definition of the public position classnested within our positionallist class position instances will be used to represent the locations of elements within the list our various positionallist methods may end up creating redundant position instances that reference the same underlying node (for examplewhen first and last are the samefor that reasonour position class defines the eq and ne special methods so that test such as = evaluates to true when two positions refer to the same node validating positions each time method of the positionallist class accepts position as parameterwe want to verify that the position is validand if soto determine the underlying node associated with the position this functionality is implemented by nonpublic method named validate internallya position maintains reference to the associated node of the linked listand also reference to the list instance that contains the specified node with the container referencewe can robustly detect when caller sends position instance that does not belong to the indicated list we are also able to detect position instance that belongs to the listbut that refers to node that is no longer part of that list recall that the delete node of the base class sets the previous and next references of deleted node to nonewe can recognize that condition to detect deprecated node access and update methods the access methods of the positionallist class are given in code fragment and the update methods are given in code fragment all of these methods trivially adapt the underlying doubly linked list implementation to support the public interface of the positional list adt those methods rely on the validate utility to "unwrapany position that is sent they also rely on make position utility to "wrapnodes as position instances to return to the usermaking sure never to return position referencing sentinel for conveniencewe have overridden the inherited insert between utility method so that ours returns position associated with the newly created node (whereas the inherited version returns the node itself
13,013
linked lists class positionallistdoublylinkedbase) """ sequential container of elements allowing positional access "" nested position class class position """an abstraction representing the location of single element "" def init (selfcontainernode) """constructor should not be invoked by user "" self container container self node node def element(self) """return the element stored at this position "" return self node element def eq (selfother) """return true if other is position representing the same location "" return type(otheris type(selfand other node is self node def ne (selfother) """return true if other does not represent the same location "" return not (self =otheropposite of eq utility method def validate(selfp) """return position nodeor raise appropriate error if invalid "" if not isinstance(pself position) raise typeerrorp must be proper position type if container is not self raise valueerrorp does not belong to this container convention for deprecated nodes if node next is none raise valueerrorp is no longer valid return node code fragment positionallist class based on doubly linked list (continues in code fragments and
13,014
utility method def make position(selfnode)"""return position instance for given node (or none if sentinel""if node is self header or node is self trailerreturn none boundary violation elsereturn self position(selfnodelegitimate position accessors def first(self)"""return the first position in the list (or none if list is empty""return self make position(self header nextdef last(self)"""return the last position in the list (or none if list is empty""return self make position(self trailer prevdef before(selfp)"""return the position just before position (or none if is first""node self validate(preturn self make position(node prevdef after(selfp)"""return the position just after position (or none if is last""node self validate(preturn self make position(node nextdef iter (self)"""generate forward iteration of the elements of the list ""cursor self firstwhile cursor is not noneyield cursor elementcursor self after(cursorcode fragment positionallist class based on doubly linked list (continued from code fragment continues in code fragment
13,015
mutators override inherited version to return positionrather than node def insert between(selfepredecessorsuccessor)"""add element between existing nodes and return new position ""node superinsert between(epredecessorsuccessorreturn self make position(nodedef add first(selfe)"""insert element at the front of the list and return new position ""return self insert between(eself headerself header nextdef add last(selfe)"""insert element at the back of the list and return new position ""return self insert between(eself trailer prevself trailerdef add before(selfpe)"""insert element into list before position and return new position ""original self validate(preturn self insert between(eoriginal prevoriginaldef add after(selfpe)"""insert element into list after position and return new position ""original self validate(preturn self insert between(eoriginaloriginal nextdef delete(selfp)"""remove and return the element at position ""original self validate(pinherited method returns element return self delete node(originaldef replace(selfpe)"""replace the element at position with return the element formerly at position ""original self validate(ptemporarily store old element old value original element replace with new element original element return the old element value return old value code fragment positionallist class based on doubly linked list (continued from code fragments and
13,016
sorting positional list in section we introduced the insertion-sort algorithmin the context of an array-based sequence in this sectionwe develop an implementation that operates on positionallistrelying on the same high-level algorithm in which each element is placed relative to growing collection of previously sorted elements we maintain variable named marker that represents the rightmost position of the currently sorted portion of list during each passwe consider the position just past the marker as the pivot and consider where the pivot' element belongs relative to the sorted portionwe use another variablenamed walkto move leftward from the markeras long as there remains preceding element with value larger than the pivot' typical configuration of these variables is diagrammed in figure python implementation of this strategy is given in code walk pivot marker figure overview of one step of our insertion-sort algorithm the shaded elementsthose up to and including markerhave already been sorted in this stepthe pivot' element should be relocated immediately before the walk position def insertion sort( ) """sort positionallist of comparable elements into nondecreasing order "" if len( otherwiseno need to sort it marker first while marker ! last) pivot after(markernext item to place value pivot element if value marker element)pivot is already sorted marker pivot pivot becomes new marker elsemust relocate pivot walk marker find leftmost item greater than value while walk ! firstand before(walkelementvalue walk before(walk delete(pivotreinsert value before walk add before(walkvaluecode fragment python code for performing insertion-sort on positional list
13,017
case studymaintaining access frequencies the positional list adt is useful in number of settings for examplea program that simulates game of cards could model each person' hand as positional list (exercise - since most people keep cards of the same suit togetherinserting and removing cards from person' hand could be implemented using the methods of the positional list adtwith the positions being determined by natural order of the suits likewisea simple text editor embeds the notion of positional insertion and deletionsince such editors typically perform all updates relative to cursorwhich represents the current position in the list of characters of text being edited in this sectionwe consider maintaining collection of elements while keeping track of the number of times each element is accessed keeping such access counts allows us to know which elements are among the most popular examples of such scenarios include web browser that keeps track of user' most accessed urlsor music collection that maintains list of the most frequently played songs for user we model this with new favorites list adt that supports the len and is empty methods as well as the followingaccess( )access the element eincrementing its access countand adding it to the favorites list if it is not already present remove( )remove element from the favorites listif present top( )return an iteration of the most accessed elements using sorted list our first approach for managing list of favorites is to store elements in linked listkeeping them in nonincreasing order of access counts we access or remove an element by searching the list from the most frequently accessed to the least frequently accessed reporting the top most accessed elements is easyas they are the first entries of the list to maintain the invariant that elements are stored in nonincreasing order of access countswe must consider how single access operation may affect the order the accessed element' count increases by oneand so it may become larger than one or more of its preceding neighbors in the listthereby violating the invariant fortunatelywe can reestablish the sorted invariant using technique similar to single pass of the insertion-sort algorithmintroduced in the previous section we can perform backward traversal of the liststarting at the position of the element whose access count has increaseduntil we locate valid position after which the element can be relocated
13,018
using the composition pattern we wish to implement favorites list by making use of positionallist for storage if elements of the positional list were simply elements of the favorites listwe would be challenged to maintain access counts and to keep the proper count with the associated element as the contents of the list are reordered we use general object-oriented design patternthe composition patternin which we define single object that is composed of two or more other objects specificallywe define nonpublic nested classitemthat stores the element and its access count as single instance we then maintain our favorites list as positionallist of item instancesso that the access count for user' element is embedded alongside it in our representation (an item is never exposed to user of favoriteslist class favoriteslist """list of elements ordered from most frequently accessed to least "" nested item class class itemslots _value _count streamline memory usage def init (selfe)the user element self value access count initially zero self count nonpublic utilities def find position(selfe) """search for element and return its position (or none if not found"" walk self data first while walk is not none and walk elementvalue ! walk self data after(walk return walk def move up(selfp) """move item at position earlier in the list based on access count ""consider moving if !self data first) cnt elementcount walk self data before(pmust shift forward if cnt walk elementcount while (walk !self data firstand cnt self data before(walkelementcount) walk self data before(walkdelete/reinsert self data add before(walkself data delete( )code fragment class favoriteslist (continues in code fragment
13,019
public methods def init (self)"""create an empty list of favorites ""will be list of item instances self data positionallistdef len (self)"""return number of entries on favorites list ""return len(self datadef is empty(self)"""return true if list is empty ""return len(self data= def access(selfe)"""access element ethereby increasing its access count ""try to locate existing element self find position(eif is nonep self data add last(self item( )if newplace at end always increment count elementcount + consider moving forward self move up(pdef remove(selfe)"""remove element from the list of favorites ""try to locate existing element self find position(eif is not nonedeleteif found self data delete(pdef top(selfk)"""generate sequence of top elements in terms of access count ""if not < <len(self)raise valueerrorillegal value for walk self data firstfor in range( )item walk elementelement of list is item report user' element yield item value walk self data after(walkcode fragment class favoriteslist (continued from code fragment
13,020
using list with the move-to-front heuristic the previous implementation of favorites list performs the access(emethod in time proportional to the index of in the favorites list that isif is the kth most popular element in the favorites listthen accessing it takes (ktime in many real-life access sequences ( web pages visited by user)once an element is accessed it is more likely to be accessed again in the near future such scenarios are said to possess locality of reference heuristicor rule of thumbthat attempts to take advantage of the locality of reference that is present in an access sequence is the move-to-front heuristic to apply this heuristiceach time we access an element we move it all the way to the front of the list our hopeof courseis that this element will be accessed again in the near future considerfor examplea scenario in which we have elements and the following series of accesseselement is accessed times element is accessed times **element is accessed times if we store the elements sorted by their access countsinserting each element the first time it is accessedthen each access to element runs in ( time each access to element runs in ( time **each access to element runs in (ntime thusthe total time for performing the series of accesses is proportional to ( nn ( which is ( on the other handif we use the move-to-front heuristicinserting each element the first time it is accessedthen each subsequent access to element takes ( time each subsequent access to element takes ( time **each subsequent access to element runs in ( time so the running time for performing all the accesses in this case is ( thusthe move-to-front implementation has faster access times for this scenario stillthe move-to-front approach is just heuristicfor there are access sequences where using the move-to-front approach is slower than simply keeping the favorites list ordered by access counts
13,021
linked lists the trade-offs with the move-to-front heuristic if we no longer maintain the elements of the favorites list ordered by their access countswhen we are asked to find the most accessed elementswe need to search for them we will implement the top(kmethod as follows we copy all entries of our favorites list into another listnamed temp we scan the temp list times in each scanwe find the entry with the largest access countremove this entry from tempand report it in the results this implementation of method top takes (kntime thuswhen is constantmethod top runs in (ntime this occursfor examplewhen we want to get the "top tenlist howeverif is proportional to nthen top runs in ( time this occursfor examplewhen we want "top %list in we will introduce data structure that will allow us to implement top in ( log ntime (see exercise - )and more advanced techniques could be used to perform top in ( log ktime we could easily achieve ( log ntime if we use standard sorting algorithm to reorder the temporary list before reporting the top (see )this approach would be preferred to the original in the case that is (log (recall the big-omega notation introduced in section to give an asymptotic lower bound on the running time of an algorithm there is more specialized sorting algorithm (see section that can take advantage of the fact that access counts are integers in order to achieve (ntime for topfor any value of implementing the move-to-front heuristic in python we give an implementation of favorites list using the move-to-front heuristic in code fragment the new favoriteslistmtf class inherits most of its functionality from the original favoriteslist as base class by our original designthe access method of the original class relies on nonpublic utility named move up to enact the potential shifting of an element forward in the listafter its access count had been incremented thereforewe implement the move-to-front heuristic by simply overriding the move up method so that each accessed element is moved directly to the front of the list (if not already therethis action is easily implemented by means of the positional list adt the more complex portion of our favoriteslistmtf class is the new definition for the top method we rely on the first of the approaches outlined aboveinserting copies of the items into temporary list and then repeatedly findingreportingand removing an element that has the largest access count of those remaining
13,022
class favoriteslistmtf(favoriteslist) """list of elements ordered with move-to-front heuristic "" we override move up to provide move-to-front semantics def move up(selfp) """move accessed item at position to front of list "" if !self data first)delete/reinsert self data add first(self data delete( ) we override top because list is no longer sorted def top(selfk) """generate sequence of top elements in terms of access count "" if not < <len(self) raise valueerrorillegal value for we begin by making copy of the original list temp positionallistpositional lists support iteration for item in self data temp add last(item we repeatedly findreportand remove element with largest count for in range( ) find and report next highest from temp highpos temp first walk temp after(highpos while walk is not none if walk elementcount highpos elementcount highpos walk walk temp after(walk we have found the element with highest count report element to user yield highpos elementvalue temp delete(highposremove from temp list code fragment class favoriteslistmtf implementing the move-to-front heuristic this class extends favoriteslist (code fragments and and overrides methods move up and top
13,023
link-based vs array-based sequences we close this by reflecting on the relative pros and cons of array-based and link-based data structures that have been introduced thus far the dichotomy between these approaches presents common design decision when choosing an appropriate implementation of data structure there is not one-size-fits-all solutionas each offers distinct advantages and disadvantages advantages of array-based sequences arrays provide ( )-time access to an element based on an integer index the ability to access the kth element for any in ( time is hallmark advantage of arrays (see section in contrastlocating the kth element in linked list requires (ktime to traverse the list from the beginningor possibly ( ktimeif traversing backward from the end of doubly linked list operations with equivalent asymptotic bounds typically run constant factor more efficiently with an array-based structure versus linked structure as an exampleconsider the typical enqueue operation for queue ignoring the issue of resizing an arraythis operation for the arrayqueue class (see code fragment involves an arithmetic calculation of the new indexan increment of an integerand storing reference to the element in the array in contrastthe process for linkedqueue (see code fragment requires the instantiation of nodeappropriate linking of nodesand an increment of an integer while this operation completes in ( time in either modelthe actual number of cpu operations will be more in the linked versionespecially given the instantiation of the new node array-based representations typically use proportionally less memory than linked structures this advantage may seem counterintuitiveespecially given that the length of dynamic array may be longer than the number of elements that it stores both array-based lists and linked lists are referential structuresso the primary memory for storing the actual objects that are elements is the same for either structure what differs is the auxiliary amounts of memory that are used by the two structures for an array-based container of elementsa typical worst case may be that recently resized dynamic array has allocated memory for object references with linked listsmemory must be devoted not only to store reference to each contained objectbut also explicit references that link the nodes so singly linked list of length already requires references (an element reference and next reference for each nodewith doubly linked listthere are references
13,024
advantages of link-based sequences link-based structures provide worst-case time bounds for their operations this is in contrast to the amortized bounds associated with the expansion or contraction of dynamic array (see section when many individual operations are part of larger computationand we only care about the total time of that computationan amortized bound is as good as worst-case bound precisely because it gives guarantee on the sum of the time spent on the individual operations howeverif data structure operations are used in real-time system that is designed to provide more immediate responses ( an operating systemweb serverair traffic control system) long delay caused by single (amortizedoperation may have an adverse effect link-based structures support ( )-time insertions and deletions at arbitrary positions the ability to perform constant-time insertion or deletion with the positionallist classby using position to efficiently describe the location of the operationis perhaps the most significant advantage of the linked list this is in stark contrast to an array-based sequence ignoring the issue of resizing an arrayinserting or deleting an element from the end of an arraybased list can be done in constant time howevermore general insertions and deletions are expensive for examplewith python' array-based list classa call to insert or pop with index uses ( time because of the loop to shift all subsequent elements (see section as an example applicationconsider text editor that maintains document as sequence of characters although users often add characters to the end of the documentit is also possible to use the cursor to insert or delete one or more characters at an arbitrary position within the document if the character sequence were stored in an array-based sequence (such as python list)each such edit operation may require linearly many characters to be shiftedleading to (nperformance for each edit operation with linked-list representationan arbitrary edit operation (insertion or deletion of character at the cursorcan be performed in ( worst-case timeassuming we are given position that represents the location of the cursor
13,025
exercises for help with exercisesplease visit the sitewww wiley com/college/goodrich reinforcement - give an algorithm for finding the second-to-last node in singly linked list in which the last node is indicated by next reference of none - describe good algorithm for concatenating two singly linked lists and mgiven only references to the first node of each listinto single list that contains all the nodes of followed by all the nodes of - describe recursive algorithm that counts the number of nodes in singly linked list - describe in detail how to swap two nodes and (and not just their contentsin singly linked list given references only to and repeat this exercise for the case when is doubly linked list which algorithm takes more timer- implement function that counts the number of nodes in circularly linked list - suppose that and are references to nodes of circularly linked listsalthough not necessarily the same list describe fast algorithm for telling if and belong to the same list - our circularqueue class of section provides rotatemethod that has semantics equivalent to enqueue( dequeue))for nonempty queue implement such method for the linkedqueue class of section without the creation of any new nodes - describe nonrecursive method for findingby link hoppingthe middle node of doubly linked list with header and trailer sentinels in the case of an even number of nodesreport the node slightly left of center as the "middle (notethis method must only use link hoppingit cannot use counter what is the running time of this methodr- give fast algorithm for concatenating two doubly linked lists and mwith header and trailer sentinel nodesinto single list - there seems to be some redundancy in the repertoire of the positional list adtas the operation add first(ecould be enacted by the alternative add before( first)elikewisel add last(emight be performed as add after( last)eexplain why the methods add first and add last are necessary
13,026
- implement functionwith calling syntax max( )that returns the maximum element from positionallist instance containing comparable elements - redo the previously problem with max as method of the positionallist classso that calling syntax maxis supported - update the positionallist class to support an additional method find( )which returns the position of the (first occurrence of element in the list (or none if not foundr- repeat the previous process using recursion your method should not contain any loops how much space does your method use in addition to the space used for lr- provide support for reversed method of the positionallist class that is similar to the given iter but that iterates the elements in reversed order - describe an implementation of the positionallist methods add last and add before realized by using only methods in the set {is emptyfirstlastprevnextadd afterand add firstr- in the favoriteslistmtf classwe rely on public methods of the positional list adt to move an element of list at position to become the first element of the listwhile keeping the relative order of the remaining elements unchanged internallythat combination of operations causes one node to be removed and new node to be inserted augment the positionallist class to support new methodmove to front( )that accomplishes this goal more directlyby relinking the existing node - given the set of element {abcdef stored in listshow the final state of the listassuming we use the move-to-front heuristic and access the elements according to the following sequence(abcdef acf bder- suppose that we have made kn total accesses to the elements in list of elementsfor some integer > what are the minimum and maximum number of elements that have been accessed fewer than timesr- let be list of items maintained according to the move-to-front heuristic describe series of (naccesses that will reverse - suppose we have an -element list maintained according to the moveto-front heuristic describe sequence of accesses that is guaranteed to take ( time to perform on - implement clearmethod for the favoriteslist class that returns the list to empty - implement reset countsmethod for the favoriteslist class that resets all elementsaccess counts to zero (while leaving the order of the list unchanged
13,027
creativity - give complete implementation of the stack adt using singly linked list that includes header sentinel - give complete implementation of the queue adt using singly linked list that includes header sentinel - implement methodconcatenate( for the linkedqueue class that takes all elements of linkedqueue and appends them to the end of the original queue the operation should run in ( time and should result in being an empty queue - give recursive implementation of singly linked list classsuch that an instance of nonempty list stores its first element and reference to list of remaining elements - describe fast recursive algorithm for reversing singly linked list - describe in detail an algorithm for reversing singly linked list using only constant amount of additional space and not using any recursion - exercise - describes leakystack abstraction implement that adt using singly linked list for storage - design forward list adt that abstracts the operations on singly linked listmuch as the positional list adt abstracts the use of doubly linked list implement forwardlist class that supports such an adt - design circular positional list adt that abstracts circularly linked list in the same way that the positional list adt abstracts doubly linked listwith notion of designated "cursorposition within the list - modify the doublylinkedbase class to include reverse method that reverses the order of the listyet without creating or destroying any nodes - modify the positionallist class to support method swap(pqthat causes the underlying nodes referenced by positions and to be exchanged for each other relink the existing nodesdo not create any new nodes - to implement the iter method of the positionallist classwe relied on the convenience of python' generator syntax and the yield statement give an alternative implementation of iter by designing nested iterator class (see section for discussion of iterators - give complete implementation of the positional list adt using doubly linked list that does not include any sentinel nodes - implement function that accepts positionallist of integers sorted in nondecreasing orderand another value and determines in (ntime if there are two elements of that sum precisely to the function should return pair of positions of such elementsif foundor none otherwise
13,028
- there is simplebut inefficientalgorithmcalled bubble-sortfor sorting list of comparable elements this algorithm scans the list - timeswherein each scanthe algorithm compares the current element with the next one and swaps them if they are out of order implement bubble sort function that takes positional list as parameter what is the running time of this algorithmassuming the positional list is implemented with doubly linked listc- to better model fifo queue in which entries may be deleted before reaching the frontdesign positionalqueue class that supports the complete queue adtyet with enqueue returning position instance and support for new methoddelete( )that removes the element associated with position from the queue you may use the adapter design pattern (section )using positionallist as your storage - describe an efficient method for maintaining favorites list lwith moveto-front heuristicsuch that elements that have not been accessed in the most recent accesses are automatically purged from the list - exercise - introduces the notion of natural join of two databases describe and analyze an efficient algorithm for computing the natural join of linked list of pairs and linked list of pairs - write scoreboard class that maintains the top scores for game application using singly linked listrather than the array that was used in section - describe method for performing card shuffle of list of elementsby converting it into two lists card shuffle is permutation where list is cut into two listsl and where is the first half of and is the second half of land then these two lists are merged into one by taking the first element in then the first element in followed by the second element in the second element in and so on projects - write simple text editor that stores and displays string of characters using the positional list adttogether with cursor object that highlights position in this string simple interface is to print the string and then to use second line of output to underline the position of the cursor your editor should support the following operationsleftmove cursor left one character (do nothing if at beginningrightmove cursor right one character (do nothing if at endinsert cinsert the character just after the cursor deletedelete the character just after the cursor (do nothing at end
13,029
- an array is sparse if most of its entries are empty ( nonea list can be used to implement such an array efficiently in particularfor each nonempty cell [ ]we can store an entry (iein lwhere is the element stored at [ithis approach allows us to represent using (mstoragewhere is the number of nonempty entries in provide such sparsearray class that minimally supports methods getitem (jand setitem (jeto provide standard indexing operations analyze the efficiency of these methods - although we have used doubly linked list to implement the positional list adtit is possible to support the adt with an array-based implementation the key is to use the composition pattern and store sequence of position itemswhere each item stores an element as well as that element' current index in the array whenever an element' place in the array is changedthe recorded index in the position must be updated to match given complete class providing such an array-based implementation of the positional list adt what is the efficiency of the various operationsp- implement cardhand class that supports person arranging group of cards in his or her hand the simulator should represent the sequence of cards using single positional list adt so that cards of the same suit are kept together implement this strategy by means of four "fingersinto the handone for each of the suits of heartsclubsspadesand diamondsso that adding new card to the person' hand or playing correct card from the hand can be done in constant time the class should support the following methodsadd card(rs)add new card with rank and suit to the hand play( )remove and return card of suit from the player' handif there is no card of suit sthen remove and return an arbitrary card from the hand iter )iterate through all cards currently in the hand all of suit( )iterate through all cards of suit that are currently in the hand notes view of data structures as collections (and other principles of object-oriented designcan be found in object-oriented design books by booch [ ]budd [ ]goldberg and robson [ ]and liskov and guttag [ our positional list adt is derived from the "positionabstraction introduced by ahohopcroftand ullman [ ]and the list adt of wood [ implementations of linked lists are discussed by knuth [
13,030
trees contents general trees tree definitions and properties the tree abstract data type computing depth and height binary trees the binary tree abstract data type properties of binary trees implementing trees linked structure for binary trees array-based representation of binary tree linked structure for general trees tree traversal algorithms preorder and postorder traversals of general trees breadth-first tree traversal inorder traversal of binary tree implementing tree traversals in python applications of tree traversals euler tours and the template method pattern case studyan expression tree exercises
13,031
general trees shuah ishbak midian medan ephah epher hanoch abida eldaah jokshan sheba dedan jacob (israelreuben simeon levi judah dan naphtali gad asher issachar zebulun dinah joseph benjamin zimran esau eliphaz reuel jeush jalam korah ishmael isaac abraham productivity experts say that breakthroughs come by thinking "nonlinearly in this we discuss one of the most important nonlinear data structures in computing--trees tree structures are indeed breakthrough in data organizationfor they allow us to implement host of algorithms much faster than when using linear data structuressuch as array-based lists or linked lists trees also provide natural organization for dataand consequently have become ubiquitous structures in file systemsgraphical user interfacesdatabasesweb sitesand other computer systems it is not always clear what productivity experts mean by "nonlinearthinkingbut when we say that trees are "nonlinear,we are referring to an organizational relationship that is richer than the simple "beforeand "afterrelationships between objects in sequences the relationships in tree are hierarchicalwith some objects being "aboveand some "belowothers actuallythe main terminology for tree data structures comes from family treeswith the terms "parent,"child,"ancestor,and "descendantbeing the most common words used to describe relationships we show an example of family tree in figure nebaioth kedar adbeel mibsam mishma dumah massa hadad tema jetur naphish kedemah figure family tree showing some descendants of abrahamas recorded in genesis -
13,032
tree definitions and properties tree is an abstract data type that stores elements hierarchically with the exception of the top elementeach element in tree has parent element and zero or more children elements tree is usually visualized by placing elements inside ovals or rectanglesand by drawing the connections between parents and children with straight lines (see figure we typically call the top element the root of the treebut it is drawn as the highest elementwith the other elements being connected below (just the opposite of botanical treeelectronics 'us & sales purchasing domestic international canada america africa manufacturing tv cd tuner overseas europe asia australia figure tree with nodes representing the organization of fictitious corporation the root stores electronics 'us the children of the root store &dsalespurchasingand manufacturing the internal nodes store salesinternationaloverseaselectronics 'usand manufacturing formal tree definition formallywe define tree as set of nodes storing elements such that the nodes have parent-child relationship that satisfies the following propertiesif is nonemptyit has special nodecalled the root of that has no parent each node of different from the root has unique parent node wevery node with parent is child of note that according to our definitiona tree can be emptymeaning that it does not have any nodes this convention also allows us to define tree recursively such that tree is either empty or consists of node rcalled the root of and (possibly emptyset of subtrees whose roots are the children of
13,033
other node relationships two nodes that are children of the same parent are siblings node is external if has no children node is internal if it has one or more children external nodes are also known as leaves example in section we discussed the hierarchical relationship between files and directories in computer' file systemalthough at the time we did not emphasize the nomenclature of file system as tree in figure we revisit an earlier example we see that the internal nodes of the tree are associated with directories and the leaves are associated with regular files in the unix and linux operating systemsthe root of the tree is appropriately called the "root directory,and is represented by the symbol "/user/rt/coursescs cs grades homeworkshw hw hw programspr pr projectspr papersbuylow sellhigh grades demosmarket figure tree representing portion of file system node is an ancestor of node if or is an ancestor of the parent of converselywe say that node is descendant of node if is an ancestor of for examplein figure cs is an ancestor of papers/and pr is descendant of cs the subtree of rooted at node is the tree consisting of all the descendants of in (including itselfin figure the subtree rooted at cs consists of the nodes cs /gradeshomeworks/programs/hw hw hw pr pr and pr edges and paths in trees an edge of tree is pair of nodes (uvsuch that is the parent of vor vice versa path of is sequence of nodes such that any two consecutive nodes in the sequence form an edge for examplethe tree in figure contains the path (cs /projects/demos/market
13,034
example the inheritance relation between classes in python program forms tree when single inheritance is used for examplein section we provided summary of the hierarchy for python' exception typesas portrayed in figure (originally figure the baseexception class is the root of that hierarchywhile all user-defined exception classes should conventionally be declared as descendants of the more specific exception class (seefor examplethe empty class we introduced in code fragment of baseexception systemexit exception keyboardinterrupt lookuperror valueerror indexerror arithmeticerror keyerror zerodivisionerror figure portion of python' hierarchy of exception types in pythonall classes are organized into single hierarchyas there exists built-in class named object as the ultimate base class it is direct or indirect base class of all other types in python (even if not declared as such when defining new classthereforethe hierarchy pictured in figure is only portion of python' complete class hierarchy as preview of the remainder of this figure portrays our own hierarchy of classes for representing various forms of tree tree binarytree arraybinarytree linkedtree linkedbinarytree figure our own inheritance hierarchy for modeling various abstractions and implementations of tree data structures in the remainder of this we provide implementations of treebinarytreeand linkedbinarytree classesand highlevel sketches for how linkedtree and arraybinarytree might be designed
13,035
ordered trees tree is ordered if there is meaningful linear order among the children of each nodethat iswe purposefully identify the children of node as being the firstsecondthirdand so on such an order is usually visualized by arranging siblings left to rightaccording to their order example the components of structured documentsuch as bookare hierarchically organized as tree whose internal nodes are partsand sectionsand whose leaves are paragraphstablesfiguresand so on (see figure the root of the tree corresponds to the book itself we couldin factconsider expanding the tree further to show paragraphs consisting of sentencessentences consisting of wordsand words consisting of characters such tree is an example of an ordered treebecause there is well-defined order among the children of each node book preface part ch ss ss part ch ch ss ss ss ss references ch ss ss figure an ordered tree associated with book let' look back at the other examples of trees that we have described thus farand consider whether the order of children is significant family tree that describes generational relationshipsas in figure is often modeled as an ordered treewith siblings ordered according to their birth in contrastan organizational chart for companyas in figure is typically considered an unordered tree likewisewhen using tree to describe an inheritance hierarchyas in figure there is no particular significance to the order among the subclasses of parent class finallywe consider the use of tree in modeling computer' file systemas in figure although an operating system often displays entries of directory in particular order ( alphabeticalchronological)such an order is not typically inherent to the file system' representation
13,036
the tree abstract data type as we did with positional lists in section we define tree adt using the concept of position as an abstraction for node of tree an element is stored at each positionand positions satisfy parent-child relationships that define the tree structure position object for tree supports the methodp element)return the element stored at position the tree adt then supports the following accessor methodsallowing user to navigate the various positions of treet root)return the position of the root of tree tor none if is empty is root( )return true if position is the root of tree parent( )return the position of the parent of position por none if is the root of num children( )return the number of children of position children( )generate an iteration of the children of position is leaf( )return true if position does not have any children len( )return the number of positions (and hence elementsthat are contained in tree is empty)return true if tree does not contain any positions positions)generate an iteration of all positions of tree iter( )generate an iteration of all elements stored within tree any of the above methods that accepts position as an argument should generate valueerror if that position is invalid for if tree is orderedthen children(preports the children of in the natural order if is leafthen children(pgenerates an empty iteration in similar regardif tree is emptythen both positionsand iter(tgenerate empty iterations we will discuss general means for iterating through all positions of tree in sections we do not define any methods for creating or modifying trees at this point we prefer to describe different tree update methods in conjunction with specific implementations of the tree interfaceand specific applications of trees
13,037
tree abstract base class in python in discussing the object-oriented design principle of abstraction in section we noted that public interface for an abstract data type is often managed in python via duck typing for examplewe defined the notion of the public interface for queue adt in section and have since presented several classes that implement the queue interface ( arrayqueue in section linkedqueue in section circularqueue in section howeverwe never gave any formal definition of the queue adt in pythonall of the concrete implementations were self-contained classes that just happen to adhere to the same public interface more formal mechanism to designate the relationships between different implementations of the same abstraction is through the definition of one class that serves as an abstract base classvia inheritancefor one or more concrete classes (see section we choose to define tree classin code fragment that serves as an abstract base class corresponding to the tree adt our reason for doing so is that there is quite bit of useful code that we can provideeven at this level of abstractionallowing greater code reuse in the concrete tree implementations we later define the tree class provides definition of nested position class (which is also abstract)and declarations of many of the accessor methods included in the tree adt howeverour tree class does not define any internal representation for storing treeand five of the methods given in that code fragment remain abstract (rootparentnum childrenchildrenand len )each of these methods raises notimplementederror ( more formal approach for defining abstract base classes and abstract methodsusing python' abc moduleis described in section the subclasses are responsible for overriding abstract methodssuch as childrento provide working implementation for each behaviorbased on their chosen internal representation although the tree class is an abstract base classit includes several concrete methods with implementations that rely on calls to the abstract methods of the class in defining the tree adt in the previous sectionwe declare ten accessor methods five of those are the ones we left as abstractin code fragment the other five can be implemented based on the former code fragment provides concrete implementations for methods is rootis leafand is empty in section we will explore general algorithms for traversing tree that can be used to provide concrete implementations of the positions and iter methods within the tree class the beauty of this design is that the concrete methods defined within the tree abstract base class will be inherited by all subclasses this promotes greater code reuseas there will be no need for those subclasses to reimplement such behaviors we note thatwith the tree class being abstractthere is no reason to create direct instance of itnor would such an instance be useful the class exists to serve as base for inheritanceand users will create instances of concrete subclasses
13,038
class tree """abstract base class representing tree structure "" nested position class class position """an abstraction representing the location of single element "" def element(self) """return the element stored at this position "" raise notimplementederrormust be implemented by subclass def eq (selfother) """return true if other position represents the same location "" raise notimplementederrormust be implemented by subclass def ne (selfother) """return true if other does not represent the same location "" return not (self =otheropposite of eq abstract methods that concrete subclass must support def root(self) """return position representing the tree root (or none if empty"" raise notimplementederrormust be implemented by subclass def parent(selfp) """return position representing parent (or none if is root"" raise notimplementederrormust be implemented by subclass def num children(selfp) """return the number of children that position has "" raise notimplementederrormust be implemented by subclass def children(selfp) """generate an iteration of positions representing children "" raise notimplementederrormust be implemented by subclass def len (self) """return the total number of elements in the tree "" raise notimplementederrormust be implemented by subclass code fragment portion of our tree abstract base class (continued in code fragment
13,039
concrete methods implemented in this class def is root(selfp)"""return true if position represents the root of the tree ""return self root= def is leaf(selfp)"""return true if position does not have any children ""return self num children( = def is empty(self)"""return true if the tree is empty ""return len(self= code fragment some concrete methods of our tree abstract base class computing depth and height let be the position of node of tree the depth of is the number of ancestors of pexcluding itself for examplein the tree of figure the node storing international has depth note that this definition implies that the depth of the root of is the depth of can also be recursively defined as followsif is the rootthen the depth of is otherwisethe depth of is one plus the depth of the parent of based on this definitionwe present simplerecursive algorithmdepthin code fragment for computing the depth of position in tree this method calls itself recursively on the parent of pand adds to the value returned def depth(selfp)"""return the number of levels separating position from the root ""if self is root( )return elsereturn self depth(self parent( )code fragment method depth of the tree class the running time of depth(pfor position is ( )where denotes the depth of in the tree because the algorithm performs constant-time recursive step for each ancestor of thusalgorithm depth(pruns in (nworstcase timewhere is the total number of positions of because position of may have depth if all nodes form single branch although such running time is function of the input sizeit is more informative to characterize the running time in terms of the parameter as this parameter may be much smaller than
13,040
height the height of position in tree is also defined recursivelyif is leafthen the height of is otherwisethe height of is one more than the maximum of the heights of ' children the height of nonempty tree is the height of the root of for examplethe tree of figure has height in additionheight can also be viewed as follows proposition the height of nonempty tree is equal to the maximum of the depths of its leaf positions we leave the justification of this fact to an exercise ( - we present an algorithmheight implemented in code fragment as nonpublic method height of the tree class it computes the height of nonempty tree based on proposition and the algorithm depth from code fragment worksbut ( ^ worst-case time def height (self)"""return the height of the tree ""return max(self depth(pfor in self positionsif self is leaf( )code fragment method height of the tree class note that this method calls the depth method unfortunatelyalgorithm height is not very efficient we have not yet defined the positionsmethodwe will see that it can be implemented to run in (ntimewhere is the number of positions of because height calls algorithm depth(pon each leaf of its running time is ( pl ( ))where is the set of leaf positions of in the worst casethe sum pl ( is proportional to (see exercise - thusalgorithm height runs in ( worst-case time we can compute the height of tree more efficientlyin (nworst-case timeby relying instead on the original recursive definition to do thiswe will parameterize function based on position within the treeand calculate the height of the subtree rooted at that position algorithm height shown as nonpublic method height in code fragment computes the height of tree in this way time is linear in size of subtree def height (selfp)"""return the height of the subtree rooted at position ""if self is leaf( )return elsereturn max(self height (cfor in self children( )code fragment method height for computing the height of subtree rooted at position of tree
13,041
it is important to understand why algorithm height is more efficient than height the algorithm is recursiveand it progresses in top-down fashion if the method is initially called on the root of it will eventually be called once for each position of this is because the root eventually invokes the recursion on each of its childrenwhich in turn invokes the recursion on each of their childrenand so on we can determine the running time of the height algorithm by summingover all the positionsthe amount of time spent on the nonrecursive part of each call (review section for analyses of recursive processes in our implementationthere is constant amount of work per positionplus the overhead of computing the maximum over the iteration of children although we do not yet have concrete implementation of children( )we assume that such an iteration is generated in ( timewhere denotes the number of children of algorithm height spends ( time at each position to compute the maximumand its overall running time is op ( ) ( in order to complete the analysiswe make use of the following property proposition let be tree with positionsand let denote the number of children of position of thensumming over the positions of justificationeach position of with the exception of the rootis child of another positionand thus contributes one unit to the above sum by proposition the running time of algorithm height when called on the root of is ( )where is the number of positions of revisiting the public interface for our tree classthe ability to compute heights of subtrees is beneficialbut user might expect to be able to compute the height of the entire tree without explicitly designating the tree root we can wrap the nonpublic height in our implementation with public height method that provides default interpretation when invoked on tree with syntax heightsuch an implementation is given in code fragment def height(selfp=none)"""return the height of the subtree rooted at position if is nonereturn the height of the entire tree ""if is nonep self rootstart height recursion return self height (pcode fragment public method tree height that computes the height of the entire tree by defaultor subtree rooted at given positionif specified
13,042
binary trees binary tree is an ordered tree with the following properties every node has at most two children each child node is labeled as being either left child or right child left child precedes right child in the order of children of node the subtree rooted at left or right child of an internal node is called left subtree or right subtreerespectivelyof binary tree is proper if each node has either zero or two children some people also refer to such trees as being full binary trees thusin proper binary treeevery internal node has exactly two children binary tree that is not proper is improper example an important class of binary trees arises in contexts where we wish to represent number of different outcomes that can result from answering series of yes-or-no questions each internal node is associated with question starting at the rootwe go to the left or right child of the current nodedepending on whether the answer to the question is "yesor "no with each decisionwe follow an edge from parent to childeventually tracing path in the tree from the root to leaf such binary trees are known as decision treesbecause leaf position in such tree represents decision of what to do if the questions associated with ' ancestors are answered in way that leads to decision tree is proper binary tree figure illustrates decision tree that provides recommendations to prospective investor are you nervousyes no will you need to access most of the money within the next yearssavings account yes no are you willing to accept risks in exchange for higher expected returnsmoney market fund yes stock portfolio no diversified portfolio with stocksbondsand short-term instruments figure decision tree providing investment advice
13,043
example an arithmetic expression can be represented by binary tree whose leaves are associated with variables or constantsand whose internal nodes are associated with one of the operators +-xand (see figure each node in such tree has value associated with it if node is leafthen its value is that of its variable or constant if node is internalthen its value is defined by applying its operation to the values of its children an arithmetic expression tree is proper binary treesince each operator +-xand takes exactly two operands of courseif we were to allow unary operatorslike negation (-)as in "- ,then we could have an improper binary tree figure binary tree representing an arithmetic expression this tree represents the expression (((( )/(( )(( ( ) )the value associated with the internal node labeled "/is recursive binary tree definition incidentallywe can also define binary tree in recursive way such that binary tree is either empty or consists ofa node rcalled the root of that stores an element binary tree (possibly empty)called the left subtree of binary tree (possibly empty)called the right subtree of
13,044
the binary tree abstract data type as an abstract data typea binary tree is specialization of tree that supports three additional accessor methodst left( )return the position that represents the left child of por none if has no left child right( )return the position that represents the right child of por none if has no right child sibling( )return the position that represents the sibling of por none if has no sibling just as in section for the tree adtwe do not define specialized update methods for binary trees here insteadwe will consider some possible update methods when we describe specific implementations and applications of binary trees the binarytree abstract base class in python just as tree was defined as an abstract base class in section we define new binarytree class associated with the binary tree adt we rely on inheritance to define the binarytree class based upon the existing tree class howeverour binarytree class remains abstractas we still do not provide complete specifications for how such structure will be represented internallynor implementations for some necessary behaviors our python implementation of the binarytree class is given in code fragment by using inheritancea binary tree supports all the functionality that was defined for general trees ( parentis leafrootour new class also inherits the nested position class that was originally defined within the tree class definition in additionthe new class provides declarations for new abstract methods left and right that should be supported by concrete subclasses of binarytree our new class also provides two concrete implementations of methods the new sibling method is derived from the combination of leftrightand parent typicallywe identify the sibling of position as the "otherchild of ' parent howeverif is the rootit has no parentand thus no sibling alsop may be the only child of its parentand thus does not have sibling finallycode fragment provides concrete implementation of the children methodthis method is abstract in the tree class although we have still not specified how the children of node will be storedwe derive generator for the ordered children based upon the implied behavior of abstract methods left and right
13,045
trees class binarytree(tree) """abstract base class representing binary tree structure "" additional abstract methods def left(selfp) """return position representing left child return none if does not have left child "" raise notimplementederrormust be implemented by subclass def right(selfp) """return position representing right child return none if does not have right child "" raise notimplementederrormust be implemented by subclass concrete methods implemented in this class def sibling(selfp) """return position representing sibling (or none if no sibling"" parent self parent( if parent is nonep must be the root return none root has no sibling else if =self left(parent) return self right(parentpossibly none else return self left(parentpossibly none def children(selfp) """generate an iteration of positions representing children "" if self left(pis not none yield self left( if self right(pis not none yield self right(pcode fragment binarytree abstract base class that extends the existing tree abstract base class from code fragments and
13,046
properties of binary trees binary trees have several interesting properties dealing with relationships between their heights and number of nodes we denote the set of all nodes of tree at the same depth as level of in binary treelevel has at most one node (the root)level has at most two nodes (the children of the root)level has at most four nodesand so on (see figure in generallevel has at most nodes nodes level figure maximum number of nodes in the levels of binary tree we can see that the maximum number of nodes on the levels of binary tree grows exponentially as we go down the tree from this simple observationwe can derive the following properties relating the height of binary tree with its number of nodes detailed justification of these properties is left as exercise - proposition let be nonempty binary treeand let nne ni and denote the number of nodesnumber of external nodesnumber of internal nodesand height of respectively then has the following properties < < + <ne < <ni < log( < < alsoif is properthen has the following properties < < + <ne < <ni < log( < <( )/
13,047
relating internal nodes to external nodes in proper binary tree in addition to the earlier binary tree propertiesthe following relationship exists between the number of internal nodes and external nodes in proper binary tree proposition in nonempty proper binary tree with ne external nodes and ni internal nodeswe have ne ni justificationwe justify this proposition by removing nodes from and dividing them up into two "piles,an internal-node pile and an external-node pileuntil becomes empty the piles are initially empty by the endwe will show that the external-node pile has one more node than the internal-node pile we consider two casescase if has only one node vwe remove and place it on the external-node pile thusthe external-node pile has one node and the internal-node pile is empty case otherwise ( has more than one node)we remove from an (arbitraryexternal node and its parent vwhich is an internal node we place on the external-node pile and on the internal-node pile if has parent uthen we reconnect with the former sibling of was shown in figure this operationremoves one internal node and one external nodeand leaves the tree being proper binary tree repeating this operationwe eventually are left with final tree consisting of single node note that the same number of external and internal nodes have been removed and placed on their respective piles by the sequence of operations leading to this final tree nowwe remove the node of the final tree and we place it on the external-node pile thusthe the external-node pile has one more node than the internal-node pile (az ( (cfigure operation that removes an external node and its parent nodeused in the justification of proposition note that the above relationship does not holdin generalfor improper binary trees and nonbinary treesalthough there are other interesting relationships that do hold (see exercises - through -
13,048
implementing trees the tree and binarytree classes that we have defined thus far in this are both formally abstract base classes although they provide great deal of supportneither of them can be directly instantiated we have not yet defined key implementation details for how tree will be represented internallyand how we can effectively navigate between parents and children specificallya concrete implementation of tree must provide methods rootparentnum childrenchildrenlen and in the case of binarytreethe additional accessors left and right there are several choices for the internal representation of trees we describe the most common representations in this section we begin with the case of binary treesince its shape is more narrowly defined linked structure for binary trees natural way to realize binary tree is to use linked structurewith node (see figure athat maintains references to the element stored at position and to the nodes associated with the children and parent of if is the root of then the parent field of is none likewiseif does not have left child (respectivelyright child)the associated field is none the tree itself maintains an instance variable storing reference to the root node (if any)and variablecalled sizethat represents the overall number of nodes of we show such linked structure representation of binary tree in figure root size parent left right baltimore chicago new york providence seattle element ( (bfigure linked structure for representing(aa single node(ba binary tree
13,049
python implementation of linked binary tree structure in this sectionwe define concrete linkedbinarytree class that implements the binary tree adt by subclassing the binarytree class our general approach is very similar to what we used when developing the positionallist in section we define simplenonpublic node class to represent nodeand public position class that wraps node we provide validate utility for robustly checking the validity of given position instance when unwrapping itand make position utility for wrapping node as position to return to caller those definitions are provided in code fragment as formalitythe new position class is declared to inherit immediately from binarytree position technicallythe binarytree class definition (see code fragment does not formally declare such nested classit trivially inherits it from tree position minor benefit from this design is that our position class inherits the ne special method so that syntax ! is derived appropriately relative to eq our class definition continuesin code fragment with constructor and with concrete implementations for the methods that remain abstract in the tree and binarytree classes the constructor creates an empty tree by initializing root to none and size to zero these accessor methods are implemented with careful use of the validate and make position utilities to safeguard against boundary cases operations for updating linked binary tree thus farwe have provided functionality for examining an existing binary tree howeverthe constructor for our linkedbinarytree class results in an empty tree and we have not provided any means for changing the structure or content of tree we chose not to declare update methods as part of the tree or binarytree abstract base classes for several reasons firstalthough the principle of encapsulation suggests that the outward behaviors of class need not depend on the internal representationthe efficiency of the operations depends greatly upon the representation we prefer to have each concrete implementation of tree class offer the most suitable options for updating tree the second reason we do not provide update methods in the base class is that we may not want such update methods to be part of public interface there are many applications of treesand some forms of update operations that are suitable for one application may be unacceptable in another howeverif we place an update method in base classany class that inherits from that base will inherit the update method considerfor examplethe possibility of method replace(pethat replaces the element stored at position with another element such general method may be unacceptable in the context of an arithmetic expression tree (see example on page and later case study in section )because we may want to enforce that internal nodes store only operators as elements
13,050
for linked binary treesa reasonable set of update methods to support for general usage are the followingt add root( )create root for an empty treestoring as the elementand return the position of that rootan error occurs if the tree is not empty add left(pe)create new node storing element elink the node as the left child of position pand return the resulting positionan error occurs if already has left child add right(pe)create new node storing element elink the node as the right child of position pand return the resulting positionan error occurs if already has right child replace(pe)replace the element stored at position with element eand return the previously stored element delete( )remove the node at position preplacing it with its childif anyand return the element that had been stored at pan error occurs if has two children attach(pt )attach the internal structure of trees and respectivelyas the left and right subtrees of leaf position of tand reset and to empty treesan error condition occurs if is not leaf we have specifically chosen this collection of operations because each can be implemented in ( worst-case time with our linked representation the most complex of these are delete and attachdue to the case analyses involving the various parent-child relationships and boundary conditionsyet there remains only constant number of operations to perform (the implementation of both methods could be greatly simplified if we used tree representation with sentinel nodeakin to our treatment of positional listssee exercise - to avoid the problem of undesirable update methods being inherited by subclasses of linkedbinarytreewe have chosen an implementation in which none of the above methods are publicly supported insteadwe provide nonpublic versions of eachfor exampleproviding the underscored delete in lieu of public delete our implementations of these six update methods are provided in code fragments and in particular applicationssubclasses of linkedbinarytree can invoke the nonpublic methods internallywhile preserving public interface that is appropriate for the application subclass may also choose to wrap one or more of the nonpublic update methods with public method to expose it to the user we leave as an exercise ( - )the task of defining mutablelinkedbinarytree subclass that provides public methods wrapping each of these six update methods
13,051
trees class linkedbinarytree(binarytree) """linked representation of binary tree structure "" lightweightnonpublic class for storing node class nodeslots _element _parent _left _right def init (selfelementparent=noneleft=noneright=none) self element element self parent parent self left left self right right class position(binarytree position) """an abstraction representing the location of single element "" def init (selfcontainernode) """constructor should not be invoked by user "" self container container self node node def element(self) """return the element stored at this position "" return self node element def eq (selfother) """return true if other is position representing the same location "" return type(otheris type(selfand other node is self node def validate(selfp) """return associated nodeif position is valid "" if not isinstance(pself position) raise typeerrorp must be proper position type if container is not self raise valueerrorp does not belong to this container convention for deprecated nodes if node parent is node raise valueerrorp is no longer valid return node def make position(selfnode) """return position instance for given node (or none if no node"" return self position(selfnodeif node is not none else none code fragment the beginning of our linkedbinarytree class (continued in code fragments through
13,052
binary tree constructor def init (self)"""create an initially empty binary tree ""self root none self size public accessors def len (self)"""return the total number of elements in the tree ""return self size def root(self)"""return the root position of the tree (or none if tree is empty""return self make position(self rootdef parent(selfp)"""return the position of parent (or none if is root""node self validate(preturn self make position(node parentdef left(selfp)"""return the position of left child (or none if no left child""node self validate(preturn self make position(node leftdef right(selfp)"""return the position of right child (or none if no right child""node self validate(preturn self make position(node rightdef num children(selfp)"""return the number of children of position ""node self validate(pcount left child exists if node left is not nonecount + right child exists if node right is not nonecount + return count code fragment public accessors for our linkedbinarytree class the class begins in code fragment and continues in code fragments and
13,053
def add root(selfe)"""place element at the root of an empty tree and return new position raise valueerror if tree nonempty ""if self root is not noneraise valueerrorroot exists self size self root self node(ereturn self make position(self rootdef add left(selfpe)"""create new left child for position pstoring element return the position of new node raise valueerror if position is invalid or already has left child ""node self validate(pif node left is not noneraise valueerrorleft child exists self size + node is its parent node left self node(enodereturn self make position(node leftdef add right(selfpe)"""create new right child for position pstoring element return the position of new node raise valueerror if position is invalid or already has right child ""node self validate(pif node right is not noneraise valueerrorright child exists self size + node is its parent node right self node(enodereturn self make position(node rightdef replace(selfpe)"""replace the element at position with eand return old element ""node self validate(pold node element node element return old code fragment nonpublic update methods for the linkedbinarytree class (continued in code fragment
13,054
def delete(selfp)"""delete the node at position pand replace it with its childif any return the element that had been stored at position raise valueerror if position is invalid or has two children ""node self validate(pif self num children( = raise valueerrorp has two children might be none child node left if node left else node right if child is not nonechild grandparent becomes parent child parent node parent if node is self rootchild becomes root self root child elseparent node parent if node is parent leftparent left child elseparent right child self size - convention for deprecated node node parent node return node element def attach(selfpt )"""attach trees and as left and right subtrees of external ""node self validate(pif not self is leaf( )raise valueerrorposition must be leaf if not type(selfis type( is type( )all trees must be same type raise typeerrortree types must match self size +len( len( attached as left subtree of node if not is empty) root parent node node left root set instance to empty root none size attached as right subtree of node if not is empty) root parent node node right root set instance to empty root none size code fragment nonpublic update methods for the linkedbinarytree class (continued from code fragment
13,055
performance of the linked binary tree implementation to summarize the efficiencies of the linked structure representationwe analyze the running times of the linkedbinarytree methodsincluding derived methods that are inherited from the tree and binarytree classesthe len methodimplemented in linkedbinarytreeuses an instance variable storing the number of nodes of and takes ( time method is emptyinherited from treerelies on single call to len and thus takes ( time the accessor methods rootleftrightparentand num children are implemented directly in linkedbinarytree and take ( time the sibling and children methods are derived in binarytree based on constant number of calls to these other accessorsso they run in ( time as well the is root and is leaf methodsfrom the tree classboth run in ( timeas is root calls root and then relies on equivalence testing of positionswhile is leaf calls left and right and verifies that none is returned by both methods depth and height were each analyzed in section the depth method at position runs in ( time where is its depththe height method on the root of the tree runs in (ntime the various update methods add rootadd leftadd rightreplacedeleteand attach (that istheir nonpublic implementationseach run in ( timeas they involve relinking only constant number of nodes per operation table summarizes the performance of the linked structure implementation of binary tree operation lenis empty rootparentleftrightsiblingchildrennum children is rootis leaf depth(pheight add rootadd leftadd rightreplacedeleteattach running time ( ( ( ( (no( table running times for the methods of an -node binary tree implemented with linked structure the space usage is (
13,056
array-based representation of binary tree an alternative representation of binary tree is based on way of numbering the positions of for every position of let (pbe the integer defined as follows if is the root of then ( if is the left child of position qthen ( ( if is the right child of position qthen ( ( the numbering function is known as level numbering of the positions in binary tree for it numbers the positions on each level of in increasing order from left to right (see figure note well that the level numbering is based on potential positions within the treenot actual positions of given treeso they are not necessarily consecutive for examplein figure ( )there are no nodes with level numbering or because the node with level numbering has no children ( ( figure binary tree level numbering(ageneral scheme(ban example
13,057
the level numbering function suggests representation of binary tree by means of an array-based structure (such as python list)with the element at position of stored at index (pof the array we show an example of an array-based representation of binary tree in figure figure representation of binary tree by means of an array one advantage of an array-based representation of binary tree is that position can be represented by the single integer ( )and that position-based methods such as rootparentleftand right can be implemented using simple arithmetic operations on the number (pbased on our formula for the level numberingthe left child of has index ( the right child of has index ( and the parent of has index  ( )/ we leave the details of complete implementation as an exercise ( - the space usage of an array-based representation depends greatly on the shape of the tree let be the number of nodes of and let fm be the maximum value of (pover all the nodes of the array requires length fm since elements range from [ to afm note that may have number of empty cells that do not refer to existing nodes of in factin the worst casen the justification of which is left as an exercise ( - in section we will see class of binary treescalled "heapsfor which thusin spite of the worst-case space usagethere are applications for which the array representation of binary tree is space efficient stillfor general binary treesthe exponential worst-case space requirement of this representation is prohibitive another drawback of an array representation is that some update operations for trees cannot be efficiently supported for exampledeleting node and promoting its child takes (ntime because it is not just the child that moves locations within the arraybut all descendants of that child
13,058
linked structure for general trees when representing binary tree with linked structureeach node explicitly maintains fields left and right as references to individual children for general treethere is no priori limit on the number of children that node may have natural way to realize general tree as linked structure is to have each node store single container of references to its children for examplea children field of node can be python list of references to the children of the node (if anysuch linked representation is schematically illustrated in figure new york parent element baltimore chicago providence children (aseattle (bfigure the linked structure for general tree(athe structure of node(ba larger portion of the data structure associated with node and its children table summarizes the performance of the implementation of general tree using linked structure the analysis is left as an exercise ( - )but we note thatby using collection to store the children of each position pwe can implement children(pby simply iterating that collection operation lenis empty rootparentis rootis leaf children(pdepth(pheight running time ( ( ( ( (ntable running times of the accessor methods of an -node general tree implemented with linked structure we let denote the number of children of position the space usage is (
13,059
tree traversal algorithms traversal of tree is systematic way of accessingor "visiting,all the positions of the specific action associated with the "visitof position depends on the application of this traversaland could involve anything from incrementing counter to performing some complex computation for in this sectionwe describe several common traversal schemes for treesimplement them in the context of our various tree classesand discuss several common applications of tree traversals preorder and postorder traversals of general trees in preorder traversal of tree the root of is visited first and then the subtrees rooted at its children are traversed recursively if the tree is orderedthen the subtrees are traversed according to the order of the children the pseudo-code for the preorder traversal of the subtree rooted at position is shown in code fragment algorithm preorder(tp)perform the "visitaction for position for each child in children(pdo preorder(tc{recursively traverse the subtree rooted at ccode fragment algorithm preorder for performing the preorder traversal of subtree rooted at position of tree figure portrays the order in which positions of sample tree are visited during an application of the preorder traversal algorithm paper title abstract ss ss ss ss ss ss ss ss ss references ss figure preorder traversal of an ordered treewhere the children of each position are ordered from left to right
13,060
postorder traversal another important tree traversal algorithm is the postorder traversal in some sensethis algorithm can be viewed as the opposite of the preorder traversalbecause it recursively traverses the subtrees rooted at the children of the root firstand then visits the root (hencethe name "postorder"pseudo-code for the postorder traversal is given in code fragment and an example of postorder traversal is portrayed in figure algorithm postorder(tp)for each child in children(pdo postorder(tc{recursively traverse the subtree rooted at cperform the "visitaction for position code fragment algorithm postorder for performing the postorder traversal of subtree rooted at position of tree paper title abstract ss ss ss ss ss ss ss ss ss references ss figure postorder traversal of the ordered tree of figure running-time analysis both preorder and postorder traversal algorithms are efficient ways to access all the positions of tree the analysis of either of these traversal algorithms is similar to that of algorithm height given in code fragment of section at each position pthe nonrecursive part of the traversal algorithm requires time ( )where is the number of children of punder the assumption that the "visititself takes ( time by proposition the overall running time for the traversal of tree is ( )where is the number of positions in the tree this running time is asymptotically optimal since the traversal must visit all the positions of the tree
13,061
breadth-first tree traversal although the preorder and postorder traversals are common ways of visiting the positions of treeanother common approach is to traverse tree so that we visit all the positions at depth before we visit the positions at depth such an algorithm is known as breadth-first traversal breadth-first traversal is common approach used in software for playing games game tree represents the possible choices of moves that might be made by player (or computerduring gamewith the root of the tree being the initial configuration for the game for examplefigure displays partial game tree for tic-tac-toe figure partial game tree for tic-tac-toewith annotations displaying the order in which positions are visited in breadth-first traversal breadth-first traversal of such game tree is often performed because computer may be unable to explore complete game tree in limited amount of time so the computer will consider all movesthen responses to those movesgoing as deep as computational time allows pseudo-code for breadth-first traversal is given in code fragment the process is not recursivesince we are not traversing entire subtrees at once we use queue to produce fifo ( first-in first-outsemantics for the order in which we visit nodes the overall running time is ( )due to the calls to enqueue and calls to dequeue algorithm breadthfirst( )initialize queue to contain rootwhile not empty do dequeue{ is the oldest entry in the queueperform the "visitaction for position for each child in children(pdo enqueue( {add ' children to the end of the queue for later visitscode fragment algorithm for performing breadth-first traversal of tree
13,062
inorder traversal of binary tree the standard preorderpostorderand breadth-first traversals that were introduced for general treescan be directly applied to binary trees in this sectionwe introduce another common traversal algorithm specifically for binary tree during an inorder traversalwe visit position between the recursive traversals of its left and right subtrees the inorder traversal of binary tree can be informally viewed as visiting the nodes of "from left to right indeedfor every position pthe inorder traversal visits after all the positions in the left subtree of and before all the positions in the right subtree of pseudo-code for the inorder traversal algorithm is given in code fragment and an example of an inorder traversal is portrayed in figure algorithm inorder( )if has left child lc then inorder(lc{recursively traverse the left subtree of pperform the "visitaction for position if has right child rc then inorder(rc{recursively traverse the right subtree of pcode fragment algorithm inorder for performing an inorder traversal of subtree rooted at position of binary tree figure inorder traversal of binary tree the inorder traversal algorithm has several important applications when using binary tree to represent an arithmetic expressionas in figure the inorder traversal visits positions in consistent order with the standard representation of the expressionas in / (albeit without parentheses
13,063
binary search trees an important application of the inorder traversal algorithm arises when we store an ordered sequence of elements in binary treedefining structure we call binary search tree let be set whose unique elements have an order relation for examples could be set of integers binary search tree for is binary tree such thatfor each position of position stores an element of sdenoted as (pelements stored in the left subtree of (if anyare less than (pelements stored in the right subtree of (if anyare greater than (pan example of binary search tree is shown in figure the above properties assure that an inorder traversal of binary search tree visits the elements in nondecreasing order figure binary search tree storing integers the solid path is traversed when searching (successfullyfor the dashed path is traversed when searching (unsuccessfullyfor we can use binary search tree for set to find whether given search value is in sby traversing path down the tree starting at the root at each internal position encounteredwe compare our search value with the element (pstored at if ( )then the search continues in the left subtree of if ( )then the search terminates successfully if ( )then the search continues in the right subtree of finallyif we reach an empty subtreethe search terminates unsuccessfully in other wordsa binary search tree can be viewed as binary decision tree (recall example )where the question asked at each internal node is whether the element at that node is less thanequal toor larger than the element being searched for we illustrate several examples of the search operation in figure note that the running time of searching in binary search tree is proportional to the height of recall from proposition that the height of binary tree with nodes can be as small as log( or as large as thusbinary search trees are most efficient when they have small height is devoted to the study of search trees
13,064
implementing tree traversals in python when first defining the tree adt in section we stated that tree should include support for the following methodst positions)generate an iteration of all positions of tree iter( )generate an iteration of all elements stored within tree at that timewe did not make any assumption about the order in which these iterations report their results in this sectionwe demonstrate how any of the tree traversal algorithms we have introduced could be used to produce these iterations to beginwe note that it is easy to produce an iteration of all elements of treeif we rely on presumed iteration of all positions thereforesupport for the iter(tsyntax can be formally provided by concrete implementation of the special method iter within the abstract base class tree we rely on python' generator syntax as the mechanism for producing iterations (see section our implementation of tree iter is given in code fragment def iter (self)"""generate an iteration of the tree elements ""for in self positions)use same order as positions(yield elementbut yield each element code fragment iterating all elements of tree instancebased upon an iteration of the positions of the tree this code should be included in the body of the tree class to implement the positions methodwe have choice of tree traversal algorithms given that there are advantages to each of those traversal orderswe will provide independent implementations of each strategy that can be called directly by user of our class we can then trivially adapt one of those as default order for the positions method of the tree adt preorder traversal we begin by considering the preorder traversal algorithm we will support public method with calling signature preorderfor tree twhich generates preorder iteration of all positions within the tree howeverthe recursive algorithm for generating preorder traversalas originally described in code fragment must be parameterized by specific position within the tree that serves as the root of subtree to traverse standard solution for such circumstance is to define nonpublic utility method with the desired recursive parameterizationand then to have the public method preorder invoke the nonpublic method upon the root of the tree our implementation of such design is given in code fragment
13,065
def preorder(self)"""generate preorder iteration of positions in the tree ""if not self is empty)for in self subtree preorder(self root))start recursion yield def subtree preorder(selfp)"""generate preorder iteration of positions in subtree rooted at ""yield visit before its subtrees for in self children( )for each child do preorder of ' subtree for other in self subtree preorder( )yield other yielding each to our caller code fragment support for performing preorder traversal of tree this code should be included in the body of the tree class formallyboth preorder and the utility subtree preorder are generators rather than perform "visitaction from within this codewe yield each position to the caller and let the caller decide what action to perform at that position the subtree preorder method is the recursive one howeverbecause we are relying on generators rather than traditional functionsthe recursion has slightly different form in order to yield all positions within the subtree of child cwe loop over the positions yielded by the recursive call self subtree preorder( )and reyield each position in the outer context note that if is leafthe for loop over self children(pis trivial (this is the base case for our recursionwe rely on similar technique in the public preorder method to re-yield all positions that are generated by the recursive process starting at the root of the treeif the tree is emptynothing is yielded at this pointwe have provided full support for the preorder generator user of the class can therefore write code such as for in preorder)"visitposition the official tree adt requires that all trees support positions method as well to use preorder traversal as the default order of iterationwe include the definition shown in code fragment within our tree class rather than loop over the results returned by the preorder callwe return the entire iteration as an object def positions(self)"""generate an iteration of the tree positions ""return self preorderreturn entire preorder iteration code fragment an implementation of the positions method for the tree class that relies on preorder traversal to generate the results
13,066
postorder traversal we can implement postorder traversal using very similar technique as with preorder traversal the only difference is that within the recursive utility for postorder we wait to yield position until after we have recursively yield the positions in its subtrees an implementation is given in code fragment def postorder(self)"""generate postorder iteration of positions in the tree ""if not self is empty)start recursion for in self subtree postorder(self root))yield def subtree postorder(selfp)"""generate postorder iteration of positions in subtree rooted at ""for in self children( )for each child for other in self subtree postorder( )do postorder of ' subtree yield other yielding each to our caller yield visit after its subtrees code fragment support for performing postorder traversal of tree this code should be included in the body of the tree class breadth-first traversal in code fragment we provide an implementation of the breadth-first traversal algorithm in the context of our tree class recall that the breadth-first traversal algorithm is not recursiveit relies on queue of positions to manage the traversal process our implementation uses the linkedqueue class from section although any implementation of the queue adt would suffice inorder traversal for binary trees the preorderpostorderand breadth-first traversal algorithms are applicable to all treesand so we include their implementations within the tree abstract base class those methods are inherited by the abstract binarytree classthe concrete linkedbinarytree classand any other dependent tree classes we might develop the inorder traversal algorithmbecause it explicitly relies on the notion of left and right child of nodeonly applies to binary trees we therefore include its definition within the body of the binarytree class we use similar technique to implement an inorder traversal (code fragment as we did with preorder and postorder traversals
13,067
def breadthfirst(self)"""generate breadth-first iteration of the positions of the tree ""if not self is empty)fringe linkedqueueknown positions not yet yielded fringe enqueue(self root)starting with the root while not fringe is empty) fringe dequeueremove from front of the queue yield report this position for in self children( )fringe enqueue(cadd children to back of queue code fragment an implementation of breadth-first traversal of tree this code should be included in the body of the tree class def inorder(self)"""generate an inorder iteration of positions in the tree ""if not self is empty)for in self subtree inorder(self root))yield def subtree inorder(selfp)"""generate an inorder iteration of positions in subtree rooted at ""if self left(pis not noneif left child existstraverse its subtree for other in self subtree inorder(self left( ))yield other yield visit between its subtrees if self right(pis not noneif right child existstraverse its subtree for other in self subtree inorder(self right( ))yield other code fragment support for performing an inorder traversal of binary tree this code should be included in the binarytree class (given in code fragment for many applications of binary treesan inorder traversal provides natural iteration we could make it the default for the binarytree class by overriding the positions method that was inherited from the tree class (see code fragment override inherited version to make inorder the default def positions(self)"""generate an iteration of the tree positions ""return self inordermake inorder the default code fragment defining the binarytree position method so that positions are reported using inorder traversal
13,068
applications of tree traversals in this sectionwe demonstrate several representative applications of tree traversalsincluding some customizations of the standard traversal algorithms table of contents when using tree to represent the hierarchical structure of documenta preorder traversal of the tree can naturally be used to produce table of contents for the document for examplethe table of contents associated with the tree from figure is displayed in figure part (aof that figure gives simple presentation with one element per linepart (bshows more attractive presentation produced by indenting each element based on its depth within the tree similar presentation could be used to display the contents of computer' file systembased on its tree representation (as in figure paper title abstract paper title abstract ( (bfigure table of contents for document represented by the tree in figure (awithout indentation(bwith indentation based on depth within the tree the unindented version of the table of contentsgiven tree can be produced with the following codefor in preorder)print( element)to produce the presentation of figure ( )we indent each element with number of spaces equal to twice the element' depth in the tree (hencethe root element was unindentedalthough we could replace the body of the above loop with str( element)))such an approach is the statement print( depth(punnecessarily inefficient although the work to produce the preorder traversal runs in (ntimebased on the analysis of section the calls to depth incur hidden cost making call to depth from every position of the tree results in ( worst-case timeas noted when analyzing the algorithm height in section
13,069
preferred approach to producing an indented table of contents is to redesign top-down recursion that includes the current depth as an additional parameter such an implementation is provided in code fragment this implementation runs in worst-case (ntime (excepttechnicallythe time it takes to print strings of increasing lengths def preorder indent(tpd) """print preorder representation of subtree of rooted at at depth ""str( element))use depth for indentation print( for in children( )child depth is + preorder indent(tcd+ code fragment efficient recursion for printing indented version of preorder traversal on complete tree the recursion should be started with form preorder indent(tt root) in the example of figure we were fortunate in that the numbering was embedded within the elements of the tree more generallywe might be interested in using preorder traversal to display the structure of treewith indentation and also explicit numbering that was not present in the tree for examplewe might display the tree from figure beginning aselectronics 'us & sales domestic international canada america this is more challengingbecause the numbers used as labels are implicit in the structure of the tree label depends on the index of each positionrelative to its siblingsalong the path from the root to the current position to accomplish the taskwe add representation of that path as an additional parameter to the recursive signature specificallywe use list of zero-indexed numbersone for each position along the downward pathother than the root (we convert those numbers to oneindexed form when printing at the implementation levelwe wish to avoid the inefficiency of duplicating such lists when sending new parameter from one level of the recursion to the next standard solution is to share the same list instance throughout the recursion at one level of the recursiona new entry is temporarily added to the end of the list before making further recursive calls in order to "leave no trace,that same block of code must remove the extraneous entry from the list before completing its task an implementation based on this approach is given in code fragment
13,070
def preorder label(tpdpath) """print labeled representation of subtree of rooted at at depth "" label join(str( + for in pathdisplayed labels are one-indexed labelp element) print( path append( path entries are zero-indexed for in children( )child depth is + preorder label(tcd+ path path[- + path popcode fragment efficient recursion for printing an indented and labeled presentation of preorder traversal parenthetic representations of tree it is not possible to reconstruct general treegiven only the preorder sequence of elementsas in figure (asome additional context is necessary for the structure of the tree to be well defined the use of indentation or numbered labels provides such contextwith very human-friendly presentation howeverthere are more concise string representations of trees that are computer-friendly in this sectionwe explore one such representation the parenthetic string representation ( of tree is recursively defined as follows if consists of single position pthen ( str( element()otherwiseit is defined recursively asp( str( element() ( ** (tk where is the root of and tk are the subtrees rooted at the children of pwhich are given in order if is an ordered tree we are using "+here to denote string concatenation as an examplethe parenthetic representation of the tree of figure would appear as follows (line breaks are cosmetic)electronics 'us ( &dsales (domesticinternational (canadas americaoverseas (africaeuropeasiaaustralia)))purchasingmanufacturing (tvcdtuner)although the parenthetic representation is essentially preorder traversalwe cannot easily produce the additional punctuation using the formal implementation of preorderas given in code fragment the opening parenthesis must be produced just before the loop over position' children and the closing parenthesis must be produced just after that loop furthermorethe separating commas must be produced the python function parenthesizeshown in code fragment is custom traversal that prints such parenthetic string representation of tree
13,071
def parenthesize(tp) """print parenthesized representation of subtree of rooted at ""use of end avoids trailing newline print( element)end if not is leaf( ) first time true for in children( )determine proper separator sep if first time else print(sependany future passes will not be the first first time false parenthesize(tcrecur on child include closing parenthesis printendcode fragment function that prints parenthetic string representation of tree computing disk space in example we considered the use of tree as model for file-system structurewith internal positions representing directories and leaves representing files in factwhen introducing the use of recursion back in we specifically examined the topic of file systems (see section although we did not explicitly model it as tree at that timewe gave an implementation of an algorithm for computing the disk usage (code fragment the recursive computation of disk space is emblematic of postorder traversalas we cannot effectively compute the total space used by directory until after we know the space that is used by its children directories unfortunatelythe formal implementation of postorderas given in code fragment does not suffice for this purpose as it visits the position of directorythere is no easy way to discern which of the previous positions represent children of that directorynor how much recursive disk space was allocated we would like to have mechanism for children to return information to the parent as part of the traversal process custom solution to the disk space problemwith each level of recursion providing return value to the (parentcalleris provided in code fragment def disk space(tp) """return total disk space for subtree of rooted at "" subtotal elementspacespace used at position for in children( )add child' space to subtotal subtotal +disk space(tc return subtotal code fragment recursive computation of disk space for tree we assume that spacemethod of each tree element reports the local space used at that position
13,072
euler tours and the template method pattern the various applications described in section demonstrate the great power of recursive tree traversals unfortunatelythey also show that the specific implementations of the preorder and postorder methods of our tree classor the inorder method of the binarytree classare not general enough to capture the range of computations we desire in some caseswe need more of blending of the approacheswith initial work performed before recurring on subtreesadditional work performed after those recursionsand in the case of binary treework performed between the two possible recursions furthermorein some contexts it was important to know the depth of positionor the complete path from the root to that positionor to return information from one level of the recursion to another for each of the previous applicationswe were able to develop custom implementation to properly adapt the recursive ideasbut the great principles of object-oriented programming introduced in section include adaptability and reusability in this sectionwe develop more general framework for implementing tree traversals based on concept known as an euler tour traversal the euler tour traversal of general tree can be informally defined as "walkaround where we start by going from the root toward its leftmost childviewing the edges of as being "wallsthat we always keep to our left (see figure figure euler tour traversal of tree the complexity of the walk is ( )because it progresses exactly two times along each of the - edges of the tree--once going downward along the edgeand later going upward along the edge to unify the concept of preorder and postorder traversalswe can think of there being two notable "visitsto each position pa "pre visitoccurs when first reaching the positionthat iswhen the walk passes immediately left of the node in our visualization "post visitoccurs when the walk later proceeds upward from that positionthat iswhen the walk passes to the right of the node in our visualization
13,073
the process of an euler tour can easily be viewed recursively in between the "pre visitand "post visitof given position will be recursive tour of each of its subtrees looking at figure as an examplethere is contiguous portion of the entire tour that is itself an euler tour of the subtree of the node with element "/that tour contains two contiguous subtoursone traversing that position' left subtree and another traversing the right subtree the pseudo-code for an euler tour traversal of subtree rooted at position is shown in code fragment algorithm eulertour(tp)perform the "pre visitaction for position for each child in children(pdo eulertour(tc{recursively tour the subtree rooted at cperform the "post visitaction for position code fragment algorithm eulertour for performing an euler tour traversal of subtree rooted at position of tree the template method pattern to provide framework that is reusable and adaptablewe rely on an interesting object-oriented software design patternthe template method pattern the template method pattern describes generic computation mechanism that can be specialized for particular application by redefining certain steps to allow customizationthe primary algorithm calls auxiliary functions known as hooks at designated steps of the process in the context of an euler tour traversalwe define two separate hooksa previsit hook that is called before the subtrees are traversedand postvisit hook that is called after the completion of the subtree traversals our implementation will take the form of an eulertour class that manages the processand defines trivial definitions for the hooks that do nothing the traversal can be customized by defining subclass of eulertour and overriding one or both hooks to provide specialized behavior python implementation our implementation of an eulertour class is provided in code fragment the primary recursive process is defined in the nonpublic tour method tour instance is created by sending reference to specific tree to the constructorand then by calling the public execute methodwhich beings the tour and returns final result of the computation
13,074
class eulertour """abstract base class for performing euler tour of tree hook previsit and hook postvisit may be overridden by subclasses "" def init (selftree) """prepare an euler tour template for given tree "" self tree tree def tree(self) """return reference to the tree being traversed "" return self tree def execute(self) """perform the tour and return any result from post visit of root "" if len(self tree start the recursion return self tour(self tree root) ] def tour(selfpdpath) """perform tour of subtree rooted at position position of current node being visited depth of in the tree path list of indices of children on path from root to """pre visitp self hook previsit(pdpath results path append( add new index to end of path before recursion for in self tree children( )recur on child subtree results append(self tour(cd+ path) path[- + increment index path popremove extraneous index from end of path "post visitp answer self hook postvisit(pdpathresults return answer can be overridden def hook previsit(selfpdpath) pass can be overridden def hook postvisit(selfpdpathresults) pass code fragment an eulertour base class providing framework for performing euler tour traversals of tree
13,075
based on our experience of customizing traversals for sample applications section we build support into the primary eulertour for maintaining the recursive depth and the representation of the recursive path through treeusing the approach that we introduced in code fragment we also provide mechanism for one recursive level to return value to another when post-processing formallyour framework relies on the following two hooks that can be specializedmethod hook previsit(pdpaththis function is called once for each positionimmediately before its subtrees (if anyare traversed parameter is position in the treed is the depth of that positionand path is list of indicesusing the convention described in the discussion of code fragment no return value is expected from this function method hook postvisit(pdpathresultsthis function is called once for each positionimmediately after its subtrees (if anyare traversed the first three parameters use the same convention as did hook previsit the final parameter is list of objects that were provided as return values from the post visits of the respective subtrees of any value returned by this call will be available to the parent of during its postvisit for more complex taskssubclasses of eulertour may also choose to initialize and maintain additional state in the form of instance variables that can be accessed within the bodies of the hooks using the euler tour framework to demonstrate the flexibility of our euler tour frameworkwe revisit the sample applications from section as simple examplean indented preorder traversalakin to that originally produced by code fragment can be generated with the simple subclass given in code fragment class preorderprintindentedtour(eulertour) def hook previsit(selfpdpath)str( element)) print( code fragment subclass of eulertour that produces an indented preorder list of tree' elements such tour would be started by creating an instance of the subclass for given tree tand invoking its execute method this could be expressed as followstour preorderprintindentedtour(ttour execute
13,076
labeled version of an indentedpreorder presentationakin to code fragment could be generated by the new subclass of eulertour shown in code fragment class preorderprintindentedlabeledtour(eulertour) def hook previsit(selfpdpath) label join(str( + for in pathlabels are one-indexed labelp element) print( code fragment subclass of eulertour that produces labeled and indentedpreorder list of tree' elements to produce the parenthetic string representationoriginally achieved with code fragment we define subclass that overrides both the previsit and postvisit hooks our new implementation is given in code fragment class parenthesizetour(eulertour) def hook previsit(selfpdpath) if path and path[- follows sibling so preface with comma printendthen print element print( element)endif has children if not self treeis leaf( )print opening parenthesis printend def hook postvisit(selfpdpathresults)if has children if not self treeis leaf( )print closing parenthesis printendcode fragment subclass of eulertour that prints parenthetic string representation of tree notice that in this implementationwe need to invoke method on the tree instance that is being traversed from within the hooks the public treemethod of the eulertour class serves as an accessor for that tree finallythe task of computing disk spaceas originally implemented in code fragment can be performed quite easily with the eulertour subclass shown in code fragment the postvisit result of the root will be returned by the call to execute class diskspacetour(eulertour) def hook postvisit(selfpdpathresults) we simply add space associated with to that of its subtrees return elementspacesum(resultscode fragment subclass of eulertour that computes disk space for tree
13,077
the euler tour traversal of binary tree in section we introduced the concept of an euler tour traversal of general graphusing the template method pattern in designing the eulertour class that class provided methods hook previsit and hook postvisit that could be overridden to customize tour in code fragment we provide binaryeulertour specialization that includes an additional hook invisit that is called once for each position--after its left subtree is traversedbut before its right subtree is traversed our implementation of binaryeulertour replaces the original tour utility to specialize to the case in which node has at most two children if node has only one childa tour differentiates between whether that is left child or right childwith the "in visittaking place after the visit of sole left childbut before the visit of sole right child in the case of leafthe three hooks are called in succession class binaryeulertour(eulertour) """abstract base class for performing euler tour of binary tree this version includes an additional hook invisit that is called after the tour of the left subtree (if any)yet before the tour of the right subtree (if any noteright child is always assigned index in patheven if no left sibling "" def tour(selfpdpath) results [nonenonewill update with results of recursions "pre visitfor self hook previsit(pdpathconsider left child if self tree left(pis not none path append( results[ self tour(self tree left( ) + path path pop"in visitfor self hook invisit(pdpathconsider right child if self tree right(pis not none path append( results[ self tour(self tree right( ) + path path pop"post visitp answer self hook postvisit(pdpathresults return answer can be overridden def hook invisit(selfpdpath)pass code fragment binaryeulertour base class providing specialized tour for binary trees the original eulertour base class was given in code fragment
13,078
figure an inorder drawing of binary tree to demonstrate use of the binaryeulertour frameworkwe develop subclass that computes graphical layout of binary treeas shown in figure the geometry is determined by an algorithm that assigns xand -coordinates to each position of binary tree using the following two rulesx(pis the number of positions visited before in an inorder traversal of (pis the depth of in in this applicationwe take the convention common in computer graphics that xcoordinates increase left to right and -coordinates increase top to bottom so the origin is in the upper left corner of the computer screen code fragment provides an implementation of binarylayout subclass that implements the above algorithm for assigning (xycoordinates to the element stored at each position of binary tree we adapt the binaryeulertour framework by introducing additional state in the form of count instance variable that represents the number of "in visitsthat we have performed the -coordinate for each position is set according to that counter class binarylayout(binaryeulertour) """class for computing ( ,ycoordinates for each node of binary tree "" def init (selftree)must call the parent constructor superinit (treeinitialize count of processed nodes self count def hook invisit(selfpdpath) -coordinate serialized by count elementsetx(self count elementsety(dy-coordinate is depth advance count of processed nodes self count + code fragment binarylayout class that computes coordinates at which to draw positions of binary tree we assume that the element type for the original tree supports setx and sety methods
13,079
case studyan expression tree in example we introduced the use of binary tree to represent the structure of an arithmetic expression in this sectionwe define new expressiontree class that provides support for constructing such treesand for displaying and evaluating the arithmetic expression that such tree represents our expressiontree class is defined as subclass of linkedbinarytreeand we rely on the nonpublic mutators to construct such trees each internal node must store string that defines binary operator ( )and each leaf must store numeric value (or string representing numeric valueour eventual goal is to build arbitrarily complex expression trees for compound arithmetic expressions such as ((( )/(( )howeverit suffices for the expressiontree class to support two basic forms of initializationexpressiontree(value)create tree storing the given value at the root expressiontree(ope )create tree storing string op at the root ( +)and with the structures of existing expressiontree instances and as the left and right subtrees of the rootrespectively such constructor for the expressiontree class is given in code fragment the class formally inherits from linkedbinarytreeso it has access to all the nonpublic update methods that were defined in section we use add root to create an initial root of the tree storing the token provided as the first parameter then we perform run-time checking of the parameters to determine whether the caller invoked the one-parameter version of the constructor (in which casewe are done)or the three-parameter form in that casewe use the inherited attach method to incorporate the structure of the existing trees as subtrees of the root composing parenthesized string representation string representation of an existing expression tree instancefor exampleas ((( + ) )/(( - )+ )can be produced by displaying tree elements using an inorder traversalbut with opening and closing parentheses inserted with preorder and postorder steprespectively in the context of an expressiontree classwe support special str method (see section that returns the appropriate string because it is more efficient to first build sequence of individual strings to be joined together (see discussion of "composing stringsin section )the implementation of str relies on nonpublicrecursive method named parenthesize recur that appends series of strings to list these methods are included in code
13,080
class expressiontree(linkedbinarytree) """an arithmetic expression tree "" def init (selftokenleft=noneright=none) """create an expression tree in single parameter formtoken should be leaf value ( ) and the expression tree will have that value at an isolated node in three-parameter versiontoken should be an operator and left and right should be existing expressiontree instances that become the operands for the binary operator ""linkedbinarytree initialization superinit if not isinstance(tokenstr) raise typeerrortoken must be string use inheritednonpublic method self add root(token if left is not nonepresumably three-parameter form if token not in +-* raise valueerrortoken must be valid operator self attach(self root)leftrightuse inheritednonpublic method def str (self) """return string representation of the expression "" pieces sequence of piecewise strings to compose self parenthesize recur(self root)pieces return join(pieces def parenthesize recur(selfpresult) """append piecewise representation of subtree to resulting list "" if self is leaf( ) result append(str( element))leaf value as string elseopening parenthesis result appendleft subtree self parenthesize recur(self left( )result result append( element)operator right subtree self parenthesize recur(self right( )resultclosing parenthesis result appendcode fragment the beginning of an expressiontree class
13,081
expression tree evaluation the numeric evaluation of an expression tree can be accomplished with simple application of postorder traversal if we know the values represented by the two subtrees of an internal positionwe can calculate the result of the computation that position designates pseudo-code for the recursive evaluation of the value represented by subtree rooted at position is given in code fragment algorithm evaluate recur( )if is leaf then return the value stored at else let be the operator stored at evaluate recur(left( ) evaluate recur(right( )return code fragment algorithm evaluate recur for evaluating the expression represented by subtree of an arithmetic expression tree rooted at position to implement this algorithm in the context of python expressiontree classwe provide public evaluate method that is invoked on instance as evaluatecode fragment provides such an implementationrelying on nonpublic evaluate recur method that computes the value of designated subtree def evaluate(self)"""return the numeric result of the expression ""return self evaluate recur(self root)def evaluate recur(selfp)"""return the numeric result of subtree rooted at ""if self is leaf( )return float( element)we assume element is numeric elseop elementleft val self evaluate recur(self left( )right val self evaluate recur(self right( )if op =return left val right val elif op =return left val right val elif op =return left val right val treat or as multiplication elsereturn left val right val code fragment support for evaluating an expressiontree instance
13,082
building an expression tree the constructor for the expressiontree classfrom code fragment provides basic functionality for combining existing trees to build larger expression trees howeverthe question still remains how to construct tree that represents an expression for given stringsuch as ((( + ) )/(( - )+ )to automate this processwe rely on bottom-up construction algorithmassuming that string can first be tokenized so that multidigit numbers are treated atomically (see exercise - )and that the expression is fully parenthesized the algorithm uses stack while scanning tokens of the input expression to find valuesoperatorsand right parentheses (left parentheses are ignored when we see an operator *we push that string on the stack when we see literal value vwe create single-node expression tree storing vand push on the stack when we see right parenthesiswe pop the top three items from the stack swhich represent subexpression ( we then construct tree using trees for and as subtrees of the root storing *and push the resulting tree back on the stack we repeat this until the expression has been processedat which time the top element on the stack is the expression tree for the total running time is (nan implementation of this algorithm is given in code fragment in the form of stand-alone function named build expression treewhich produces and returns an appropriate expressiontree instanceassuming the input has been tokenized def build expression tree(tokens) """returns an expressiontree based upon by tokenized expression "" =[we use python list as stack for in tokenst is an operator symbol if in +- * append(tpush the operator symbol consider to be literal elif not in ( append(expressiontree( )push trivial tree storing value compose new tree from three constituent parts elif = right popright subtree as per lifo op popoperator symbol left popleft subtree append(expressiontree(opleftright)repush tree we ignore left parenthesis return popcode fragment implementation of build expression tree that produces an expressiontree from sequence of tokens representing an arithmetic expression
13,083
exercises for help with exercisesplease visit the sitewww wiley com/college/goodrich reinforcement - the following questions refer to the tree of figure which node is the rootb what are the internal nodesc how many descendants does node cs haved how many ancestors does node cs havee what are the siblings of node homeworks/ which nodes are in the subtree rooted at node projects/ what is the depth of node papers/ what is the height of the treer- show tree achieving the worst-case running time for algorithm depth - give justification of proposition - what is the running time of call to height (pwhen called on position distinct from the root of (see code fragment - describe an algorithmrelying only on the binarytree operationsthat counts the number of leaves in binary tree that are the left child of their respective parent - let be an -node binary tree that may be improper describe how to represent by means of proper binary tree with (nnodes - what are the minimum and maximum number of internal and external nodes in an improper binary tree with nodesr- answer the following questions so as to justify proposition what is the minimum number of external nodes for proper binary tree with height hjustify your answer what is the maximum number of external nodes for proper binary tree with height hjustify your answer let be proper binary tree with height and nodes show that log( < <( )/ for which values of and can the above lower and upper bounds on be attained with equalityr- give proof by induction of proposition - give direct implementation of the num children method within the class binarytree
13,084
- find the value of the arithmetic expression associated with each subtree of the binary tree of figure - draw an arithmetic expression tree that has four external nodesstoring the numbers and (with each number stored in distinct external nodebut not necessarily in this order)and has three internal nodeseach storing an operator from the set {+- /}so that the value of the root is the operators may return and act on fractionsand an operator may be used more than once - draw the binary tree representation of the following arithmetic expression"((( ( ))/(( (( ) ) - justify table summarizing the running time of the methods of tree represented with linked structureby providingfor each methoda description of its implementationand an analysis of its running time - the linkedbinarytree class provides only nonpublic versions of the update methods discussed on page implement simple subclass named mutablelinkedbinarytree that provides public wrapper functions for each of the inherited nonpublic update methods - let be binary tree with nodesand let (be the level numbering function of the positions of as given in section show thatfor every position of ( < show an example of binary tree with seven nodes that attains the above upper bound on (pfor some position - show how to use the euler tour traversal to compute the level number ( )as defined in section of each position in binary tree - let be binary tree with positions that is realized with an array representation aand let (be the level numbering function of the positions of as given in section give pseudo-code descriptions of each of the methods rootparentleftrightis leafand is root - our definition of the level numbering function ( )as given in section began with the root having number some authors prefer to use level numbering (pin which the root is assigned number because it simplifies the arithmetic for finding neighboring positions redo exercise - but assuming that we use level numbering (pin which the root is assigned number - draw binary tree that simultaneously satisfies the followingeach internal node of stores single character preorder traversal of yields examfun an inorder traversal of yields mafxuen - in what order are positions visited during preorder traversal of the tree of figure
13,085
- in what order are positions visited during postorder traversal of the tree of figure - let be an ordered tree with more than one node is it possible that the preorder traversal of visits the nodes in the same order as the postorder traversal of if sogive an exampleotherwiseexplain why this cannot occur likewiseis it possible that the preorder traversal of visits the nodes in the reverse order of the postorder traversal of if sogive an exampleotherwiseexplain why this cannot occur - answer the previous question for the case when is proper binary tree with more than one node - consider the example of breadth-first traversal given in figure using the annotated numbers from that figuredescribe the contents of the queue before each pass of the while loop in code fragment to get startedthe queue has contents { before the first passand contents { before the second pass - the collections deque class supports an extend method that adds collection of elements to the end of the queue at once reimplement the breadthfirst method of the tree class to take advantage of this feature - give the output of the function parenthesize(tt root))as described in code fragment when is the tree of figure - what is the running time of parenthesize(tt root))as given in code fragment for tree with nodesr- describein pseudo-codean algorithm for computing the number of descendants of each node of binary tree the algorithm should be based on the euler tour traversal - the build expression tree method of the expressiontree class requires input that is an iterable of string tokens we used convenient example((( + ) )/(( - )+ )in which each character is its own tokenso that the string itself sufficed as input to build expression tree in generala stringsuch as ( must be explicitly tokenized into list so as to ignore whitespace and to recognize multidigit numbers as single token write utility methodtokenize(raw)that returns such list of tokens for raw string creativity - define the internal path lengthi( )of tree to be the sum of the depths of all the internal positions in likewisedefine the external path lengthe( )of tree to be the sum of the depths of all the external positions in show that if is proper binary tree with positionsthen ( (
13,086
- let be (not necessarily properbinary tree with nodesand let be the sum of the depths of all the external nodes of show that if has the minimum number of external nodes possiblethen is (nand if has the maximum number of external nodes possiblethen is ( log nc- let be (possibly improperbinary tree with nodesand let be the sum of the depths of all the external nodes of describe configuration for such that is ( such tree would be the worst case for the asymptotic running time of method height (code fragment - for tree let ni denote the number of its internal nodesand let ne denote the number of its external nodes show that if every internal node in has exactly childrenthen ne ni - two ordered trees and are said to be isomorphic if one of the following holdsboth and are empty the roots of and have the same number > of subtreesand the ith such subtree of is isomorphic to the ith such subtree of for design an algorithm that tests whether two given ordered trees are isomorphic what is the running time of your algorithmc- show that there are more than improper binary trees with internal nodes such that no pair are isomorphic (see exercise - - if we exclude isomorphic trees (see exercise - )exactly how many proper binary trees exist with exactly leavesc- add support in linkedbinarytree for methoddelete subtree( )that removes the entire subtree rooted at position pmaking sure to maintain the count on the size of the tree what is the running time of your implementationc- add support in linkedbinarytree for methodswap( , )that has the effect of restructuring the tree so that the node referenced by takes the place of the node referenced by qand vice versa make sure to properly handle the case when the nodes are adjacent - we can simplify parts of our linkedbinarytree implementation if we make use of of single sentinel nodereferenced as the sentinel member of the tree instancesuch that the sentinel is the parent of the real root of the treeand the root is referenced as the left child of the sentinel furthermorethe sentinel will take the place of none as the value of the left or right member for node without such child give new implementation of the update methods delete and attachassuming such representation
13,087
- describe how to clone linkedbinarytree instance representing proper binary treewith use of the attach method - describe how to clone linkedbinarytree instance representing (not necessarily properbinary treewith use of the add left and add right methods - we can define binary tree representation for an ordered general tree as follows (see figure )for each position of there is an associated position of if is leaf of then in does not have left childotherwise the left child of is where is the first child of in if has sibling ordered immediately after it in then is the right child of in otherwise does not have right child given such representation of general ordered tree answer each of the following questionsa is preorder traversal of equivalent to preorder traversal of is postorder traversal of equivalent to postorder traversal of is an inorder traversal of equivalent to one of the standard traversals of if sowhich onea ( (bfigure representation of tree with binary tree(atree (bbinary tree for the dashed edges connect nodes of that are siblings in - give an efficient algorithm that computes and printsfor every position of tree the element of followed by the height of ' subtree - give an ( )-time algorithm for computing the depths of all positions of tree where is the number of nodes of - the path length of tree is the sum of the depths of all positions in describe linear-time method for computing the path length of tree - the balance factor of an internal position of proper binary tree is the difference between the heights of the right and left subtrees of show how to specialize the euler tour traversal of section to print the balance factors of all the internal nodes of proper binary tree
13,088
- given proper binary tree define the reflection of to be the binary tree such that each node in is also in but the left child of in is ' right child in and the right child of in is ' left child in show that preorder traversal of proper binary tree is the same as the postorder traversal of ' reflectionbut in reverse order - let the rank of position during traversal be defined such that the first element visited has rank the second element visited has rank and so on for each position in tree let pre(pbe the rank of in preorder traversal of let post(pbe the rank of in postorder traversal of let depth(pbe the depth of pand let desc(pbe the number of descendants of pincluding itself derive formula defining post(pin terms of desc( )depth( )and pre( )for each node in - design algorithms for the following operations for binary tree preorder next( )return the position visited after in preorder traversal of (or none if is the last node visitedinorder next( )return the position visited after in an inorder traversal of (or none if is the last node visitedpostorder next( )return the position visited after in postorder traversal of (or none if is the last node visitedwhat are the worst-case running times of your algorithmsc- to implement the preorder method of the linkedbinarytree classwe relied on the convenience of python' generator syntax and the yield statement give an alternative implementation of preorder that returns an explicit instance of nested iterator class (see section for discussion of iterators - algorithm preorder draw draws binary tree by assigning xand ycoordinates to each position such that (pis the number of nodes preceding in the preorder traversal of and (pis the depth of in show that the drawing of produced by preorder draw has no pairs of crossing edges redraw the binary tree of figure using preorder draw - redo the previous problem for the algorithm postorder draw that is similar to preorder draw except that it assigns (pto be the number of nodes preceding position in the postorder traversal - design an algorithm for drawing general treesusing style similar to the inorder traversal approach for drawing binary trees - exercise - described the walk function of the os module this function performs traversal of the implicit tree represented by the file system read the formal documentation for the functionand in particular its use of an optional boolean parameter named topdown describe how its behavior relates to tree traversal algorithms described in this
13,089
sales domestic international canada america africa overseas europe (aasia australia sales domestic international canada america overseas africa europe asia australia (bfigure (atree (bindented parenthetic representation of - the indented parenthetic representation of tree is variation of the parenthetic representation of (see code fragment that uses indentation and line breaks as illustrated in figure give an algorithm that prints this representation of tree - let be binary tree with positions define roman position to be position in such that the number of descendants in ' left subtree differ from the number of descendants in ' right subtree by at most describe linear-time method for finding each position of such that is not roman positionbut all of ' descendants are roman - let be tree with positions define the lowest common ancestor (lcabetween two positions and as the lowest position in that has both and as descendants (where we allow position to be descendant of itself given two positions and qdescribe an efficient algorithm for finding the lca of and what is the running time of your algorithmc- let be binary tree with positionsandfor any position in let denote the depth of in the distance between two positions and in is dq da where is the lowest common ancestor (lcaof and the diameter of is the maximum distance between two positions in describe an efficient algorithm for finding the diameter of what is the running time of your algorithmc- suppose each position of binary tree is labeled with its value (pin level numbering of design fast method for determining (afor the lowest common ancestor (lca)aof two positions and in given (pand (qyou do not need to find position ajust value (ac- give an alternative implementation of the build expression tree method of the expressiontree class that relies on recursion to perform an implicit euler tour of the tree that is being built
13,090
- note that the build expression tree function of the expressiontree class is written in such way that leaf token can be any stringfor exampleit parses the expression ( *( + )howeverwithin the evaluate methodan error would occur when attempting to convert leaf token to number modify the evaluate method to accept an optional python dictionary that can be used to map such string variables to numeric valueswith syntax such as evaluate( : : : }in this waythe same algebraic expression can be evaluated using different values - as mentioned in exercise - postfix notation is an unambiguous way of writing an arithmetic expression without parentheses it is defined so that if "(exp op (exp )is normal (infixfully parenthesized expression with operation opthen its postfix equivalent is "pexp pexp op"where pexp is the postfix version of exp and pexp is the postfix version of exp the postfix version of single number or variable is just that number or variable sofor examplethe postfix version of the infix expression "(( ( ))/ is " /implement postfix method of the expressiontree class of section that produces the postfix notation for the given expression projects - implement the binary tree adt using the array-based representation described in section - implement the tree adt using linked structure as described in section provide reasonable set of update methods for your tree - the memory usage for the linkedbinarytree class can be streamlined by removing the parent reference from each nodeand instead having each position instance keep memberpaththat is list of nodes representing the entire path from the root to that position (this generally saves memory because there are typically relatively few stored position instances reimplement the linkedbinarytree class using this strategy - slicing floor plan divides rectangle with horizontal and vertical sides using horizontal and vertical cuts (see figure slicing floor plan can be represented by proper binary treecalled slicing treewhose internal nodes represent the cutsand whose external nodes represent the basic rectangles into which the floor plan is decomposed by the cuts (see figure the compaction problem for slicing floor plan is defined as follows assume that each basic rectangle of slicing floor plan is assigned minimum width and minimum height the compaction problem is to find the smallest possible height and width for each rectangle of the slicing floor plan that is compatible with the minimum dimensions
13,091
(ac (bfigure (aslicing floor plan(bslicing tree associated with the floor plan of the basic rectangles namelythis problem requires the assignment of values (pand (pto each position of the slicing tree such thatif is leaf whose basic rectangle has minimum width if is an internal positionassociated with max( () ( ) horizontal cutwith left child and right (pchild if is an internal positionassociated with ( (ra vertical cutwith left child and right child (ph if is leaf node whose basic rectangle has minimum height ( (rif is an internal positionassociated with horizontal cutwith left child and right child if is an internal positionassociated with max( () ( ) vertical cutwith left child and right child design data structure for slicing floor plans that supports the operationscreate floor plan consisting of single basic rectangle decompose basic rectangle by means of horizontal cut decompose basic rectangle by means of vertical cut assign minimum height and width to basic rectangle draw the slicing tree associated with the floor plan compact and draw the floor plan
13,092
- write program that can play tic-tac-toe effectively (see section to do thisyou will need to create game tree which is tree where each position corresponds to game configurationwhichin this caseis representation of the tic-tac-toe board (see section the root corresponds to the initial configuration for each internal position in the children of correspond to the game states we can reach from ' game state in single legal move for the appropriate playera (the first playeror (the second playerpositions at even depths correspond to moves for and positions at odd depths correspond to moves for leaves are either final game states or are at depth beyond which we do not want to explore we score each leaf with value that indicates how good this state is for player in large gameslike chesswe have to use heuristic scoring functionbut for small gameslike tic-tac-toewe can construct the entire game tree and score leaves as + - indicating whether player has windrawor lose in that configuration good algorithm for choosing moves is minimax in this algorithmwe assign score to each internal position in such that if represents ' turnwe compute ' score as the maximum of the scores of ' children (which corresponds to ' optimal play from pif an internal node represents ' turnthen we compute ' score as the minimum of the scores of ' children (which corresponds to ' optimal play from pp- implement the tree adt using the binary tree representation described in exercise - you may adapt the linkedbinarytree implementation - write program that takes as input general tree and position of and converts to another tree with the same set of position adjacenciesbut now with as its root notes discussions of the classic preorderinorderand postorder tree traversal methods can be found in knuth' fundamental algorithms book [ the euler tour traversal technique comes from the parallel algorithms communityit is introduced by tarjan and vishkin [ and is discussed by jaja [ and by karp and ramachandran [ the algorithm for drawing tree is generally considered to be part of the "folkloreof graph-drawing algorithms the reader interested in graph drawing is referred to the book by di battistaeadestamassiaand tollis [ and the survey by tamassia and liotta [ the puzzle in exercise - was communicated by micha sharir
13,093
priority queues contents the priority queue abstract data type priorities the priority queue adt implementing priority queue the composition design pattern implementation with an unsorted list implementation with sorted list heaps the heap data structure implementing priority queue with heap array-based representation of complete binary tree python heap implementation analysis of heap-based priority queue bottom-up heap construction python' heapq module sorting with priority queue selection-sort and insertion-sort heap-sort adaptable priority queues locators implementing an adaptable priority queue exercises
13,094
the priority queue abstract data type priorities in we introduced the queue adt as collection of objects that are added and removed according to the first-infirst-out (fifoprinciple company' customer call center embodies such model in which waiting customers are told "calls will be answered in the order that they were received in that settinga new call is added to the back of the queueand each time customer service representative becomes availablehe or she is connected with the call that is removed from the front of the call queue in practicethere are many applications in which queue-like structure is used to manage objects that must be processed in some waybut for which the first-infirst-out policy does not suffice considerfor examplean air-traffic control center that has to decide which flight to clear for landing from among many approaching the airport this choice may be influenced by factors such as each plane' distance from the runwaytime spent waiting in holding patternor amount of remaining fuel it is unlikely that the landing decisions are based purely on fifo policy there are other situations in which "first comefirst servepolicy might seem reasonableyet for which other priorities come into play to use another airline analogysuppose certain flight is fully booked an hour prior to departure because of the possibility of cancellationsthe airline maintains queue of standby passengers hoping to get seat although the priority of standby passenger is influenced by the check-in time of that passengerother considerations include the fare paid and frequent-flyer status so it may be that an available seat is given to passenger who has arrived later than anotherif such passenger is assigned better priority by the airline agent in this we introduce new abstract data type known as priority queue this is collection of prioritized elements that allows arbitrary element insertionand allows the removal of the element that has first priority when an element is added to priority queuethe user designates its priority by providing an associated key the element with the minimum key will be the next to be removed from the queue (thusan element with key will be given priority over an element with key although it is quite common for priorities to be expressed numericallyany python object may be used as keyas long as the object type supports consistent meaning for the test bfor any instances and bso as to define natural order of the keys with such generalityapplications may develop their own notion of priority for each element for exampledifferent financial analysts may assign different ratings ( prioritiesto particular assetsuch as share of stock
13,095
the priority queue adt formallywe model an element and its priority as key-value pair we define the priority queue adt to support the following methods for priority queue pp add(kv)insert an item with key and value into priority queue min)return tuple( , )representing the key and value of an item in priority queue with minimum key (but do not remove the item)an error occurs if the priority queue is empty remove min)remove an item with minimum key from priority queue pand return tuple( , )representing the key and value of the removed iteman error occurs if the priority queue is empty is empty)return true if priority queue does not contain any items len( )return the number of items in priority queue priority queue may have multiple entries with equivalent keysin which case methods min and remove min may report an arbitrary choice of item having minimum key values may be any type of object in our initial model for priority queuewe assume that an element' key remains fixed once it has been added to priority queue in section we consider an extension that allows user to update an element' key within the priority queue example the following table shows series of operations and their effects on an initially empty priority queue the "priority queuecolumn is somewhat deceiving since it shows the entries as tuples and sorted by key such an internal representation is not required of priority queue operation add( ,ap add( ,cp add( ,bp add( ,dp minp remove minp remove minlen(pp remove minp remove minp is emptyp remove minreturn value ( , ( , ( , ( , ( ,ctrue "errorpriority queue {( , ){( , )( , ){( , )( , )( , ){( , )( , )( , )( , ){( , )( , )( , )( , ){( , )( , )( , ){( , )( , ){( , )( , ){( , ){{{
13,096
implementing priority queue in this sectionwe show how to implement priority queue by storing its entries in positional list (see section we provide two realizationsdepending on whether or not we keep the entries in sorted by key the composition design pattern one challenge in implementing priority queue is that we must keep track of both an element and its keyeven as items are relocated within our data structure this is reminiscent of case study from section in which we maintain access counts with each element in that settingwe introduced the composition design patterndefining an item class that assured that each element remained paired with its associated count in our primary data structure for priority queueswe will use composition to store items internally as pairs consisting of key and value to implement this concept for all priority queue implementationswe provide priorityqueuebase class (see code fragment that includes definition for nested class named item we define the syntax bfor item instances and bto be based upon the keys class priorityqueuebase """abstract base class for priority queue "" class item """lightweight composite to store priority queue items ""slots _key _value def init (selfkv) self key self value def lt (selfother)compare items based on their keys return self key other key concrete method assuming abstract len def is empty(self) """return true if the priority queue is empty "" return len(self= code fragment priorityqueuebase class with nested item class that composes key and value into single object for conveniencewe provide concrete implementation of is empty that is based on presumed len impelementation
13,097
implementation with an unsorted list in our first concrete implementation of priority queuewe store entries within an unsorted list our unsortedpriorityqueue class is given in code fragment inheriting from the priorityqueuebase class introduced in code fragment for internal storagekey-value pairs are represented as compositesusing instances of the inherited item class these items are stored within positionallistidentified as the data member of our class we assume that the positional list is implemented with doubly-linked listas in section so that all operations of that adt execute in ( time we begin with an empty list when new priority queue is constructed at all timesthe size of the list equals the number of key-value pairs currently stored in the priority queue for this reasonour priority queue len method simply returns the length of the internal data list by the design of our priorityqueuebase classwe inherit concrete implementation of the is empty method that relies on call to our len method each time key-value pair is added to the priority queuevia the add methodwe create new item composite for the given key and valueand add that item to the end of the list such an implementation takes ( time the remaining challenge is that when min or remove min is calledwe must locate the item with minimum key because the items are not sortedwe must inspect all entries to find one with minimum key for conveniencewe define nonpublic find min utility that returns the position of an item with minimum key knowledge of the position allows the remove min method to invoke the delete method on the positional list the min method simply uses the position to retrieve the item when preparing key-value tuple to return due to the loop for finding the minimum keyboth min and remove min methods run in (ntimewhere is the number of entries in the priority queue summary of the running times for the unsortedpriorityqueue class is given in table operation len is empty add min remove min running time ( ( ( (no(ntable worst-case running times of the methods of priority queue of size nrealized by means of an unsorteddoubly linked list the space requirement is (
13,098
class unsortedpriorityqueue(priorityqueuebase)base class defines item """ min-oriented priority queue implemented with an unsorted list "" nonpublic utility def find min(self) """return position of item with minimum key ""is empty inherited from base class if self is empty) raise emptypriority queue is empty small self data first walk self data after(small while walk is not none if walk elementsmall element) small walk walk self data after(walk return small def init (self) """create new empty priority queue "" self data positionallist def len (self) """return the number of items in the priority queue "" return len(self data def add(selfkeyvalue) """add key-value pair "" self data add last(self item(keyvalue) def min(self) """return but do not remove ( ,vtuple with minimum key "" self find min item element return (item keyitem value def remove min(self) """remove and return ( ,vtuple with minimum key "" self find min item self data delete( return (item keyitem valuecode fragment an implementation of priority queue using an unsorted list the parent class priorityqueuebase is given in code fragment and the positionallist class is from section
13,099
implementation with sorted list an alternative implementation of priority queue uses positional listyet maintaining entries sorted by nondecreasing keys this ensures that the first element of the list is an entry with the smallest key our sortedpriorityqueue class is given in code fragment the implementation of min and remove min are rather straightforward given knowledge that the first element of list has minimum key we rely on the first method of the positional list to find the position of the first itemand the delete method to remove the entry from the list assuming that the list is implemented with doubly linked listoperations min and remove min take ( time this benefit comes at costhoweverfor method add now requires that we scan the list to find the appropriate position to insert the new item our implementation starts at the end of the listwalking backward until the new key is smaller than an existing itemin the worst caseit progresses until reaching the front of the list thereforethe add method takes (nworst-case timewhere is the number of entries in the priority queue at the time the method is executed in summarywhen using sorted list to implement priority queueinsertion runs in linear timewhereas finding and removing the minimum can be done in constant time comparing the two list-based implementations table compares the running times of the methods of priority queue realized by means of sorted and unsorted listrespectively we see an interesting tradeoff when we use list to implement the priority queue adt an unsorted list supports fast insertions but slow queries and deletionswhereas sorted list allows fast queries and deletionsbut slow insertions operation len is empty add min remove min unsorted list ( ( ( (no(nsorted list ( ( (no( ( table worst-case running times of the methods of priority queue of size nrealized by means of an unsorted or sorted listrespectively we assume that the list is implemented by doubly linked list the space requirement is (