id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
21,900 | shrinking the underlying array desirable property of queue implementation is to have its space usage be th(nwhere is the current number of elements in the queue our arrayqueue implementationas given in code fragments and does not have this property it expands the underlying array when enqueue is called with the queue at full capacitybut the dequeue implementation never shrinks the underlying array as consequencethe capacity of the underlying array is proportional to the maximum number of elements that have ever been stored in the queuenot the current number of elements we discussed this very issue on page in the context of dynamic arraysand in subsequent exercises - through - of that robust approach is to reduce the array to half of its current sizewhenever the number of elements stored in it falls below one fourth of its capacity we can implement this strategy by adding the following two lines of code in our dequeue methodjust after reducing self size at line of code fragment to reflect the loss of an element if self size len(self data/ self resize(len(self data/ analyzing the array-based queue implementation table describes the performance of our array-based implementation of the queue adtassuming the improvement described above for occasionally shrinking the size of the array with the exception of the resize utilityall of the methods rely on constant number of statements involving arithmetic operationscomparisonsand assignments thereforeeach method runs in worst-case ( timeexcept for enqueue and dequeuewhich have amortized bounds of ( timefor reasons similar to those given in section operation enqueue(eq dequeueq firstq is emptylen(qamortized running time ( ) ( ) ( ( ( table performance of an array-based implementation of queue the bounds for enqueue and dequeue are amortized due to the resizing of the array the space usage is ( )where is the current number of elements in the queue |
21,901 | double-ended queues we next consider queue-like data structure that supports insertion and deletion at both the front and the back of the queue such structure is called doubleended queueor dequewhich is usually pronounced "deckto avoid confusion with the dequeue method of the regular queue adtwhich is pronounced like the abbreviation " the deque abstract data type is more general than both the stack and the queue adts the extra generality can be useful in some applications for examplewe described restaurant using queue to maintain waitlist occassionallythe first person might be removed from the queue only to find that table was not availabletypicallythe restaurant will re-insert the person at the first position in the queue it may also be that customer at the end of the queue may grow impatient and leave the restaurant (we will need an even more general data structure if we want to model customers leaving the queue from other positions the deque abstract data type to provide symmetrical abstractionthe deque adt is defined so that deque supports the following methodsd add first( )add element to the front of deque add last( )add element to the back of deque delete first)remove and return the first element from deque dan error occurs if the deque is empty delete last)remove and return the last element from deque dan error occurs if the deque is empty additionallythe deque adt will include the following accessorsd first)return (but do not removethe first element of deque dan error occurs if the deque is empty last)return (but do not removethe last element of deque dan error occurs if the deque is empty is empty)return true if deque does not contain any elements len( )return the number of elements in deque din pythonwe implement this with the special method len |
21,902 | example the following table shows series of operations and their effects on an initially empty deque of integers operation add last( add first( add first( firstd delete lastlen(dd delete lastd delete lastd add first( lastd add first( is emptyd lastreturn value false deque [ [ [ [ [ [ [ [[ [ [ [ [ implementing deque with circular array we can implement the deque adt in much the same way as the arrayqueue class provided in code fragments and of section (so much so that we leave the details of an arraydeque implementation to exercise - we recommend maintaining the same three instance variablesdatasizeand front whenever we need to know the index of the back of the dequeor the first available slot beyond the back of the dequewe use modular arithmetic for the computation for exampleour implementation of the lastmethod uses the index back (self front self size len(self dataour implementation of the arraydeque add last method is essentially the same as that for arrayqueue enqueueincluding the reliance on resize utility likewisethe implementation of the arraydeque delete first method is the same as arrayqueue dequeue implementations of add first and delete last use similar techniques one subtlety is that call to add first may need to wrap around the beginning of the arrayso we rely on modular arithmetic to circularly decrement the indexas self front (self front len(self datacyclic shift the efficiency of an arraydeque is similar to that of an arrayqueuewith all operations having ( running timebut with that bound being amortized for operations that may change the size of the underlying list |
21,903 | deques in the python collections module an implementation of deque class is available in python' standard collections module summary of the most commonly used behaviors of the collections deque class is given in table it uses more asymmetric nomenclature than our adt our deque adt len(dd add firstd add lastd delete firstd delete lastd firstd lastcollections deque len(dd appendleftd appendd popleftd popd[ [- [jd[jval cleard rotate(kd remove(ed count(edescription number of elements add to beginning add to end remove from beginning remove from end access first element access last element access arbitrary entry by index modify arbitrary entry by index clear all contents circularly shift rightward steps remove first matching element count number of matches for table comparison of our deque adt and the collections deque class the collections deque interface was chosen to be consistent with established naming conventions of python' list classfor which append and pop are presumed to act at the end of the list thereforeappendleft and popleft designate an operation at the beginning of the list the library deque also mimics list in that it is an indexed sequenceallowing arbitrary access or modification using the [jsyntax the library deque constructor also supports an optional maxlen parameter to force fixed-length deque howeverif call to append at either end is invoked when the deque is fullit does not throw an errorinsteadit causes one element to be dropped from the opposite side that iscalling appendleft when the deque is full causes an implicit pop from the right side to make room for the new element the current python distribution implements collections deque with hybrid approach that uses aspects of circular arraysbut organized into blocks that are themselves organized in doubly linked list ( data structure that we will introduce in the next the deque class is formally documented to guarantee ( )-time operations at either endbut ( )-time worst-case operations when using index notation near the middle of the deque |
21,904 | exercises for help with exercisesplease visit the sitewww wiley com/college/goodrich reinforcement - what values are returned during the following series of stack operationsif executed upon an initially empty stackpush( )push( )pop()push( )push( )pop()pop()push( )push( )pop()push( )push( )pop()pop()push( )pop()pop( - suppose an initially empty stack has executed total of push operations top operationsand pop operations of which raised empty errors that were caught and ignored what is the current size of sr- implement function with signature transfer(stthat transfers all elements from stack onto stack tso that the element that starts at the top of is the first to be inserted onto tand the element at the bottom of ends up at the top of - give recursive method for removing all the elements from stack - implement function that reverses list of elements by pushing them onto stack in one orderand writing them back to the list in reversed order - give precise and complete definition of the concept of matching for grouping symbols in an arithmetic expression your definition may be recursive - what values are returned during the following sequence of queue operationsif executed on an initially empty queueenqueue( )enqueue( )dequeue()enqueue( )enqueue( )dequeue()dequeue()enqueue( )enqueue( )dequeue()enqueue( )enqueue( )dequeue()dequeue()enqueue( )dequeue()dequeue( - suppose an initially empty queue has executed total of enqueue operations first operationsand dequeue operations of which raised empty errors that were caught and ignored what is the current size of qr- had the queue of the previous problem been an instance of arrayqueue that used an initial array of capacity and had its size never been greater than what would be the final value of the front instance variabler- consider what happens if the loop in the arrayqueue resize method at lines - of code fragment had been implemented asfor in range(self size)self data[kold[krather than old[walkgive clear explanation of what could go wrong |
21,905 | - give simple adapter that implements our queue adt while using collections deque instance for storage - what values are returned during the following sequence of deque adt operationson initially empty dequeadd first( )add last( )add last( )add first( )back)delete first)delete last)add last( )first)last)add last( )delete first)delete firstr- suppose you have deque containing the numbers ( )in this order suppose further that you have an initially empty queue give code fragment that uses only and (and no other variablesand results in storing the elements in the order ( - repeat the previous problem using the deque and an initially empty stack creativity - suppose alice has picked three distinct integers and placed them into stack in random order write shortstraight-line piece of pseudo-code (with no loops or recursionthat uses only one comparison and only one variable xyet that results in variable storing the largest of alice' three integers with probability / argue why your method is correct - modify the arraystack implementation so that the stack' capacity is limited to maxlen elementswhere maxlen is an optional parameter to the constructor (that defaults to noneif push is called when the stack is at full capacitythrow full exception (defined similarly to emptyc- in the previous exercisewe assume that the underlying list is initially empty redo that exercisethis time preallocating an underlying list with length equal to the stack' maximum capacity - show how to use the transfer functiondescribed in exercise - and two temporary stacksto replace the contents of given stack with those same elementsbut in reversed order - in code fragment we assume that opening tags in html have form as with more generallyhtml allows optional attributes to be expressed as part of an opening tag the general form used is for examplea table can be given border and additional padding by using an opening tag of modify code fragment so that it can properly match tagseven when an opening tag may include one or more such attributes - describe nonrecursive algorithm for enumerating all permutations of the numbers { nusing an explicit stack |
21,906 | stacksqueuesand deques - show how to use stack and queue to generate all possible subsets of an -element set nonrecursively - postfix notation is an unambiguous way of writing an arithmetic expression without parentheses it is defined so that if "(exp op (exp )is normalfully parenthesized expression whose operation is opthe postfix version of this 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 for examplethe postfix version of "(( ( ))/ is " /describe nonrecursive way of evaluating an expression in postfix notation - suppose you have three nonempty stacks rsand describe sequence of operations that results in storing all elements originally in below all of ' original elementswith both sets of those elements in their original order the final configuration for should be the same as its original configuration for exampleif [ ] [ ]and [ ]the final configuration should have [ and [ - describe how to implement the stack adt using single queue as an instance variableand only constant additional local memory within the method bodies what is the running time of the push()pop()and top(methods for your designc- describe how to implement the queue adt using two stacks as instance variablessuch that all queue operations execute in amortized ( time give formal proof of the amortized bound - describe how to implement the double-ended queue adt using two stacks as instance variables what are the running times of the methodsc- suppose you have stack containing elements and queue that is initially empty describe how you can use to scan to see if it contains certain element xwith the additional constraint that your algorithm must return the elements back to in their original order you may only use sqand constant number of other variables - modify the arrayqueue implementation so that the queue' capacity is limited to maxlen elementswhere maxlen is an optional parameter to the constructor (that defaults to noneif enqueue is called when the queue is at full capacitythrow full exception (defined similarly to emptyc- in certain applications of the queue adtit is common to repeatedly dequeue an elementprocess it in some wayand then immediately enqueue the same element modify the arrayqueue implementation to include rotatemethod that has semantics identical to the combinationq enqueue( dequeue)howeveryour implementation should be more efficient than making two separate calls (for examplebecause there is no need to modify size |
21,907 | - alice has two queuesq and rwhich can store integers bob gives alice odd integers and even integers and insists that she store all integers in and they then play game where bob picks or at random and then applies the round-robin schedulerdescribed in the to the chosen queue random number of times if the last number to be processed at the end of this game was oddbob wins otherwisealice wins how can alice allocate integers to queues to optimize her chances of winningwhat is her chance of winningc- suppose bob has four cows that he wants to take across bridgebut only one yokewhich can hold up to two cowsside by sidetied to the yoke the yoke is too heavy for him to carry across the bridgebut he can tie (and untiecows to it in no time at all of his four cowsmazie can cross the bridge in minutesdaisy can cross it in minutescrazy can cross it in minutesand lazy can cross it in minutes of coursewhen two cows are tied to the yokethey must go at the speed of the slower cow describe how bob can get all his cows across the bridge in minutes projects - give complete arraydeque implementation of the double-ended queue adt as sketched in section - give an array-based implementation of double-ended queue supporting all of the public behaviors shown in table for the collections deque classincluding use of the maxlen optional parameter when lengthlimited deque is fullprovide semantics similar to the collections deque classwhereby call to insert an element on one end of deque causes an element to be lost from the opposite side - implement program that can input an expression in postfix notation (see exercise - and output its value - the introduction of section notes that stacks are often used to provide "undosupport in applications like web browser or text editor while support for undo can be implemented with an unbounded stackmany applications provide only limited support for such an undo historywith fixed-capacity stack when push is invoked with the stack at full capacityrather than throwing full exception (as described in exercise - ) more typical semantic is to accept the pushed element at the top while "leakingthe oldest element from the bottom of the stack to make room give an implementation of such leakystack abstractionusing circular array with appropriate storage capacity this class should have public interface similar to the bounded-capacity stack in exercise - but with the desired leaky semantics when full |
21,908 | - when share of common stock of some company is soldthe capital gain (orsometimeslossis the difference between the share' selling price and the price originally paid to buy it this rule is easy to understand for single sharebut if we sell multiple shares of stock bought over long period of timethen we must identify the shares actually being sold standard accounting principle for identifying which shares of stock were sold in such case is to use fifo protocol--the shares sold are the ones that have been held the longest (indeedthis is the default method built into several personal finance software packagesfor examplesuppose we buy shares at $ each on day shares at $ on day shares at $ on day and then sell shares on day at $ each then applying the fifo protocol means that of the shares sold were bought on day were bought on day and were bought on day the capital gain in this case would therefore be (- )or $ write program that takes as input sequence of transactions of the form "buy share(sat eachor "sell share(sat each,assuming that the transactions occur on consecutive days and the values and are integers given this input sequencethe output should be the total capital gain (or lossfor the entire sequenceusing the fifo protocol to identify shares - design an adt for two-colordouble-stack adt that consists of two stacks--one "redand one "blue"--and has as its operations color-coded versions of the regular stack adt operations for examplethis adt should support both red push operation and blue push operation give an efficient implementation of this adt using single array whose capacity is set at some value that is assumed to always be larger than the sizes of the red and blue stacks combined notes we were introduced to the approach of defining data structures first in terms of their adts and then in terms of concrete implementations by the classic books by ahohopcroftand ullman [ exercises - and - are similar to interview questions said to be from well-known software company for further study of abstract data typessee liskov and guttag [ ]cardelli and wegner [ ]or demurjian [ |
21,909 | linked lists contents singly linked lists implementing stack with singly linked list implementing queue with singly linked list circularly linked lists round-robin schedulers implementing queue with circularly linked list doubly linked lists basic implementation of doubly linked list implementing deque with doubly linked list the positional list adt the positional list abstract data type doubly linked list implementation sorting positional list case studymaintaining access frequencies using sorted list using list with the move-to-front heuristic link-based vs array-based sequences exercises |
21,910 | in we carefully examined python' array-based list classand in we demonstrated use of that class in implementing the classic stackqueueand dequeue adts python' list class is highly optimizedand often great choice for storage with that saidthere are some notable disadvantages the length of dynamic array might be longer than the actual number of elements that it stores amortized bounds for operations may be unacceptable in real-time systems insertions and deletions at interior positions of an array are expensive in this we introduce data structure known as linked listwhich provides an alternative to an array-based sequence (such as python listboth array-based sequences and linked lists keep elements in certain orderbut using very different style an array provides the more centralized representationwith one large chunk of memory capable of accommodating references to many elements linked listin contrastrelies on more distributed representation in which lightweight objectknown as nodeis allocated for each element each node maintains reference to its element and one or more references to neighboring nodes in order to collectively represent the linear order of the sequence we will demonstrate trade-off of advantages and disadvantages when contrasting array-based sequences and linked lists elements of linked list cannot be efficiently accessed by numeric index kand we cannot tell just by examining node if it is the secondfifthor twentieth node in the list howeverlinked lists avoid the three disadvantages noted above for array-based sequences singly linked lists singly linked listin its simplest formis collection of nodes that collectively form linear sequence each node stores reference to an object that is an element of the sequenceas well as reference to the next node of the list (see figures and msp element next figure example of node instance that forms part of singly linked list the node' element member references an arbitrary object that is an element of the sequence (the airport code mspin this example)while the next member references the subsequent node of the linked list (or none if there is no further node |
21,911 | lax msp atl head bos tail figure example of singly linked list whose elements are strings indicating airport codes the list instance maintains member named head that identifies the first node of the listand in some applications another member named tail that identifies the last node of the list the none object is denoted as the first and last node of linked list are known as the head and tail of the listrespectively by starting at the headand moving from one node to another by following each node' next referencewe can reach the tail of the list we can identify the tail as the node having none as its next reference this process is commonly known as traversing the linked list because the next reference of node can be viewed as link or pointer to another nodethe process of traversing list is also known as link hopping or pointer hopping linked list' representation in memory relies on the collaboration of many objects each node is represented as unique objectwith that instance storing reference to its element and reference to the next node (or noneanother object represents the linked list as whole minimallythe linked list instance must keep reference to the head of the list without an explicit reference to the headthere would be no way to locate that node (or indirectlyany othersthere is not an absolute need to store direct reference to the tail of the listas it could otherwise be located by starting at the head and traversing the rest of the list howeverstoring an explicit reference to the tail node is common convenience to avoid such traversal in similar regardit is common for the linked list instance to keep count of the total number of nodes that comprise the list (commonly described as the size of the list)to avoid the need to traverse the list to count the nodes for the remainder of this we continue to illustrate nodes as objectsand each node' "nextreference as pointer howeverfor the sake of simplicitywe illustrate node' element embedded directly within the node structureeven though the element isin factan independent object for examplefigure is more compact illustration of the linked list from figure lax head msp atl bos tail figure compact illustration of singly linked listwith elements embedded in the nodes (rather than more accurately drawn as references to external objects |
21,912 | inserting an element at the head of singly linked list an important property of linked list is that it does not have predetermined fixed sizeit uses space proportionally to its current number of elements when using singly linked listwe can easily insert an element at the head of the listas shown in figure and described with pseudo-code in code fragment the main idea is that we create new nodeset its element to the new elementset its next link to refer to the current headand then set the list' head to point to the new node head msp atl bos (anewest head lax msp atl bos (bnewest lax head msp atl bos (cfigure insertion of an element at the head of singly linked list(abefore the insertion(bafter creation of new node(cafter reassignment of the head reference algorithm add first(le)newest node( {create new node instance storing reference to element enewest next head {set new node' next to reference the old head nodel head newest {set variable head to reference the new nodel size size {increment the node countcode fragment inserting new element at the beginning of singly linked list note that we set the next pointer of the new node before we reassign variable head to it if the list were initially empty ( head is none)then natural consequence is that the new node has its next reference set to none |
21,913 | inserting an element at the tail of singly linked list we can also easily insert an element at the tail of the listprovided we keep reference to the tail nodeas shown in figure in this casewe create new nodeassign its next reference to noneset the next reference of the tail to point to this new nodeand then update the tail reference itself to this new node we give the details in code fragment tail msp atl bos (atail msp atl newest bos mia (btail msp atl bos newest mia (cfigure insertion at the tail of singly linked list(abefore the insertion(bafter creation of new node(cafter reassignment of the tail reference note that we must set the next link of the tail in (bbefore we assign the tail variable to point to the new node in (calgorithm add last(le)newest node( {create new node instance storing reference to element enewest next none {set new node' next to reference the none objectl tail next newest {make old tail node point to new nodel tail newest {set variable tail to reference the new nodel size size {increment the node countcode fragment inserting new node at the end of singly linked list note that we set the next pointer for the old tail node before we make variable tail point to the new node this code would need to be adjusted for inserting onto an empty listsince there would not be an existing tail node |
21,914 | removing an element from singly linked list removing an element from the head of singly linked list is essentially the reverse operation of inserting new element at the head this operation is illustrated in figure and given in detail in code fragment head lax msp atl bos (ahead lax msp atl bos (bhead msp atl bos (cfigure removal of an element at the head of singly linked list(abefore the removal(bafter "linking outthe old head(cfinal configuration algorithm remove first( )if head is none then indicate an errorthe list is empty head head next {make head point to next node (or none) size size {decrement the node countcode fragment removing the node at the beginning of singly linked list unfortunatelywe cannot easily delete the last node of singly linked list even if we maintain tail reference directly to the last node of the listwe must be able to access the node before the last node in order to remove the last node but we cannot reach the node before the tail by following next links from the tail the only way to access this node is to start from the head of the list and search all the way through the list but such sequence of link-hopping operations could take long time if we want to support such an operation efficientlywe will need to make our list doubly linked (as we do in section |
21,915 | implementing stack with singly linked list in this sectionwe demonstrate use of singly linked list by providing complete python implementation of the stack adt (see section in designing such an implementationwe need to decide whether to model the top of the stack at the head or at the tail of the list there is clearly best choice herewe can efficiently insert and delete elements in constant time only at the head since all stack operations affect the topwe orient the top of the stack at the head of our list to represent individual nodes of the listwe develop lightweight node class this class will never be directly exposed to the user of our stack classso we will formally define it as nonpublicnested class of our eventual linkedstack class (see section for discussion of nested classesthe definition of the node class is shown in code fragment class node"""lightweightnonpublic class for storing singly linked node ""slots _element _next streamline memory usage def init (selfelementnext)self element element self next next initialize node' fields reference to user' element reference to next node code fragment lightweight node class for singly linked list node has only two instance variableselement and next we intentionally define slots to streamline the memory usage (see page of section for discussion)because there may potentially be many node instances in single list the constructor of the node class is designed for our convenienceallowing us to specify initial values for both fields of newly created node complete implementation of our linkedstack class is given in code fragments and each stack instance maintains two variables the head member is reference to the node at the head of the list (or noneif the stack is emptywe keep track of the current number of elements with the size instance variablefor otherwise we would be forced to traverse the entire list to count the number of elements when reporting the size of the stack the implementation of push essentially mirrors the pseudo-code for insertion at the head of singly linked list as outlined in code fragment when we push new element onto the stackwe accomplish the necessary changes to the linked structure by invoking the constructor of the node class as followsself head self node(eself headcreate and link new node note that the next field of the new node is set to the existing top nodeand then self head is reassigned to the new node |
21,916 | linked lists class linkedstack """lifo stack implementation using singly linked list for storage "" nested node class class node """lightweightnonpublic class for storing singly linked node ""slots _element _next streamline memory usage initialize node' fields def init (selfelementnext)reference to user' element self element element reference to next node self next next stack methods def init (self) """create an empty stack ""reference to the head node self head none number of stack elements self size def len (self) """return the number of elements in the stack "" return self size def is empty(self) """return true if the stack is empty "" return self size = def push(selfe) """add element to the top of the stack ""create and link new node self head self node(eself head self size + def top(self) """return (but do not removethe element at the top of the stack raise empty exception if the stack is empty "" if self is empty) raise emptystack is empty top of stack is at head of list return self head element code fragment implementation of stack adt using singly linked list (continued in code fragment |
21,917 | def pop(self)"""remove and return the element from the top of the stack ( liforaise empty exception if the stack is empty ""if self is empty)raise emptystack is empty answer self head element bypass the former top node self head self head next self size - return answer code fragment implementation of stack adt using singly linked list (continued from code fragment when implementing the top methodthe goal is to return the element that is at the top of the stack when the stack is emptywe raise an empty exceptionas originally defined in code fragment of when the stack is nonemptyself head is reference to the first node of the linked list the top element can be identified as self head element our implementation of pop essentially mirrors the pseudo-code given in code fragment except that we maintain local reference to the element that is stored at the node that is being removedand we return that element to the caller of pop the analysis of our linkedstack operations is given in table we see that all of the methods complete in worst-case constant time this is in contrast to the amortized bounds for the arraystack that were given in table operation push(es pops toplen(ss is emptyrunning time ( ( ( ( ( table performance of our linkedstack implementation all bounds are worstcase and our space usage is ( )where is the current number of elements in the stack |
21,918 | implementing queue with singly linked list as we did for the stack adtwe can use singly linked list to implement the queue adt while supporting worst-case ( )-time for all operations because we need to perform operations on both ends of the queuewe will explicitly maintain both head reference and tail reference as instance variables for each queue the natural orientation for queue is to align the front of the queue with the head of the listand the back of the queue with the tail of the listbecause we must be able to enqueue elements at the backand dequeue them from the front (recall from the introduction of section that we are unable to efficiently remove elements from the tail of singly linked list our implementation of linkedqueue class is given in code fragments and class linkedqueue """fifo queue implementation using singly linked list for storage "" class node """lightweightnonpublic class for storing singly linked node "" (omitted hereidentical to that of linkedstack node def init (self) """create an empty queue "" self head none self tail none number of queue elements self size def len (self) """return the number of elements in the queue "" return self size def is empty(self) """return true if the queue is empty "" return self size = def first(self) """return (but do not removethe element at the front of the queue "" if self is empty) raise emptyqueue is empty front aligned with head of list return self head element code fragment implementation of queue adt using singly linked list (continued in code fragment |
21,919 | 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 answer self head element self head self head next self size - special case as queue is empty if self is empty)removed head had been the tail self tail none return answer def enqueue(selfe)"""add an element to the back of queue ""node will be new tail node newest self node(enoneif self is empty)special casepreviously empty self head newest elseself tail next newest update reference to tail node self tail newest self size + code fragment implementation of queue adt using singly linked list (continued from code fragment many aspects of our implementation are similar to that of the linkedstack classsuch as the definition of the nested node class our implementation of dequeue for linkedqueue is similar to that of pop for linkedstackas both remove the head of the linked list howeverthere is subtle difference because our queue must accurately maintain the tail reference (no such variable was maintained for our stackin generalan operation at the head has no effect on the tailbut when dequeue is invoked on queue with one elementwe are simultaneously removing the tail of the list we therefore set self tail to none for consistency there is similar complication in our implementation of enqueue the newest node always becomes the new tail yet distinction is made depending on whether that new node is the only node in the list in that caseit also becomes the new headotherwise the new node must be linked immediately after the existing tail node in terms of performancethe linkedqueue is similar to the linkedstack in that all operations run in worst-case constant timeand the space usage is linear in the current number of elements |
21,920 | circularly linked lists in section we introduced the notion of "circulararray and demonstrated its use in implementing the queue adt in realitythe notion of circular array was artificialin that there was nothing about the representation of the array itself that was circular in structure it was our use of modular arithmetic when "advancingan index from the last slot to the first slot that provided such an abstraction in the case of linked liststhere is more tangible notion of circularly linked listas we can have the tail of the list use its next reference to point back to the head of the listas shown in figure we call such structure circularly linked list lax msp atl head bos tail figure example of singly linked list with circular structure circularly linked list provides more general model than standard linked list for data sets that are cyclicthat iswhich do not have any particular notion of beginning and end figure provides more symmetric illustration of the same circular list structure as figure lax msp bos current atl figure example of circular linked listwith current denoting reference to select node circular view similar to figure could be usedfor exampleto describe the order of train stops in the chicago loopor the order in which players take turns during game even though circularly linked list has no beginning or endper sewe must maintain reference to particular node in order to make use of the list we use the identifier current to describe such designated node by setting current current nextwe can effectively advance through the nodes of the list |
21,921 | round-robin schedulers to motivate the use of circularly linked listwe consider round-robin schedulerwhich iterates through collection of elements in circular fashion and "serviceseach element by performing given action on it such scheduler is usedfor exampleto fairly allocate resource that must be shared by collection of clients for instanceround-robin scheduling is often used to allocate slices of cpu time to various applications running concurrently on computer round-robin scheduler could be implemented with the general queue adtby repeatedly performing the following steps on queue (see figure ) dequeue( service element enqueue(ethe queue deque the next element service the next element enqueue the serviced element shared service figure the three iterative steps for round-robin scheduling using queue if we use of the linkedqueue class of section for such an applicationthere is unnecessary effort in the combination of dequeue operation followed soon after by an enqueue of the same element one node is removed from the listwith appropriate adjustments to the head of the list and the size decrementedand then new node is created to reinsert at the tail of the list and the size is incremented if using circularly linked listthe effective transfer of an item from the "headof the list to the "tailof the list can be accomplished by advancing reference that marks the boundary of the queue we will next provide an implementation of circularqueue class that supports the entire queue adttogether with an additional methodrotate)that moves the first element of the queue to the back ( similar method is supported by the deque class of python' collections modulesee table with this operationa round-robin schedule can more efficiently be implemented by repeatedly performing the following steps service element front( rotate( |
21,922 | linked lists implementing queue with circularly linked list to implement the queue adt using circularly linked listwe rely on the intuition of figure in which the queue has head and tailbut with the next reference of the tail linked to the head given such modelthere is no need for us to explicitly store references to both the head and the tailas long as we keep reference to the tailwe can always find the head by following the tail' next reference code fragments and provide an implementation of circularqueue class based on this model the only two instance variables are tailwhich is reference to the tail node (or none when empty)and sizewhich is the current number of elements in the queue when an operation involves the front of the queuewe recognize self tail next as the head of the queue when enqueue is calleda new node is placed just after the tail but before the current headand then the new node becomes the tail in addition to the traditional queue operationsthe circularqueue class supports rotate method that more efficiently enacts the combination of removing the front element and reinserting it at the back of the queue with the circular representationwe simply set self tail self tail next to make the old head become the new tail (with the node after the old head becoming the new head class circularqueue """queue implementation using circularly linked list for storage "" class node """lightweightnonpublic class for storing singly linked node "" (omitted hereidentical to that of linkedstack node def init (self) """create an empty queue ""will represent tail of queue self tail none number of queue elements self size def len (self) """return the number of elements in the queue "" return self size def is empty(self) """return true if the queue is empty "" return self size = code fragment implementation of circularqueue classusing circularly linked list as storage (continued in code fragment |
21,923 | 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 |
21,924 | 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 |
21,925 | 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 |
21,926 | 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 |
21,927 | 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 |
21,928 | 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 |
21,929 | 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 |
21,930 | 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 |
21,931 | 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 |
21,932 | 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 - |
21,933 | 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 |
21,934 | 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 |
21,935 | 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 |
21,936 | 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 |
21,937 | 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 |
21,938 | 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 |
21,939 | 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 |
21,940 | 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 |
21,941 | 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 |
21,942 | 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 |
21,943 | 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 |
21,944 | 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 |
21,945 | 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 |
21,946 | 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 |
21,947 | 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 |
21,948 | 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 |
21,949 | - 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 |
21,950 | 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 |
21,951 | - 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 |
21,952 | - 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 [ |
21,953 | 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 |
21,954 | 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 - |
21,955 | 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 |
21,956 | 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 |
21,957 | 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 |
21,958 | 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 |
21,959 | 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 |
21,960 | 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 |
21,961 | 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 |
21,962 | 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 |
21,963 | 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 |
21,964 | 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 |
21,965 | 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 |
21,966 | 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 |
21,967 | 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 |
21,968 | 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 |
21,969 | 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( < <( )/ |
21,970 | 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 - |
21,971 | 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 |
21,972 | 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 |
21,973 | 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 |
21,974 | 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 |
21,975 | 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 |
21,976 | 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 |
21,977 | 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 |
21,978 | 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 ( |
21,979 | 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 |
21,980 | 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 |
21,981 | 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 ( |
21,982 | 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 |
21,983 | 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 |
21,984 | 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 |
21,985 | 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 |
21,986 | 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 |
21,987 | 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 |
21,988 | 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 |
21,989 | 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 |
21,990 | 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 |
21,991 | 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 |
21,992 | 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 |
21,993 | 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 |
21,994 | 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 |
21,995 | 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 |
21,996 | 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 |
21,997 | 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 |
21,998 | 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 |
21,999 | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.