id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
21,000 | popular page |
21,001 | exercises for source code and help with exercisesplease visit java datastructures net reinforcement - draw representation of an initially empty array list after performing the following sequence of operationsadd( , )add( , )add( , )add( , )add( , )add( , )add( , )add( , - give justification of the running times shown in table for the methods of an array list implemented with (nonexpandingarray - give an adapter class to support the stack interface using the methods of the array list adt - redo the justification of proposition assuming that the the cost of growing the array from size to size is cyber-dollars how much should each push operation be charged to make the amortization workr- give pseudo-code descriptions of algorithms for performing the methods addbefore( , )addfirst( )and addlast(eof the node list adtassuming the list is implemented using doubly linked list - draw pictures illustrating each of the major steps in the algorithms given in the previous exercise - provide the details of an array implementation of the node list adtincluding how to perform the methods add before and addafter - |
21,002 | of code fragment that are not included in code fragments - describe nonrecursive method for reversing node list represented with doubly linked list using single pass through the list (you may use the internal node pointersr- given the set of element {abcdefstored in listshow the final state of the listassuming we use the move-to-front heuristic and access the elements according to the following sequence(abcdefacf, , ,er- suppose we are keeping track of access counts in list of elements suppose further that we have made kn total accesses to the elements in lfor some integer > what are the minimum and maximum number of elements that have been accessed fewer than timesr- give pseudo-code describing how to implement all the operations in the array list adt using an array in circular fashion what is the running time for each of these methodsr- using the sequence interface methodsdescribe recursive method for determining if sequence of integers contains given integer your method should not contain any loops how much space does your method use in addition to the space used for sr- briefly describe how to perform new sequence method makefirst(pthat moves an element of sequence at position to be the first element in while keeping the relative ordering of the remaining elements in unchanged that ismakefirst(pperforms move-to-front your method should run in ( time if is implemented with doubly linked list - describe how to use an array list and an int field to implement an iterator include pseudo-code fragments describing hasnext(and next( |
21,003 | describe how to create an iterator for node list that returns every other element in the list - suppose we are maintaining collection of elements such thateach time we add new element to the collectionwe copy the contents of into new array list of just the right size what is the running time of adding elements to an initially empty collection in this caser- describe an implementation of the methods addlast and add before realized by using only methods in the set {isemptycheckpositionfirstlastprevnextaddafteraddfirstr- let be maintained to be list of items ordered by decreasing access count describe series of ( accesses that will reverse - let be list of items maintained according to the move-to-front heuristic describe series of (naccesses that will reverse creativity - give pseudo-code for the methods of new classshrinkingarraylistthat extends the class arrayindexlist shown in code fragment and adds methodshrinktofit()which replaces the underlying array with an array whose capacity is exactly equal to the number of elements currently in the array list - describe what changes need to be made to the extendable array implementation given in code fragment in order to shrink by half the size of the array any time the number of elements in the array list goes below / - |
21,004 | previous exercisethe following series of operations takes (ntime(in push operations on an array list with initial capacity (iin pop (removal of the last elementoperations - show how to improve the implementation of method add in code fragment so thatin case of an overflowthe elements are copied into their final place in the new arraythat isno shifting should be done in this case - consider an implementation of the array list adt using an extendable arraybut instead of copying the elements of the array list into an array of double the size (that isfrom to nwhen its capacity is reachedwe copy the elements into an array with / additional cellsgoing from capacity to / show that performing sequence of push operations (that isinsertions at the endstill runs in (ntime in this case - the nodepositionlist implementation given in code fragments does not do any error checks to test if given position is actually member of this particular list for exampleif is position in list and we call addafter(peon different list tthen we actually will add the element to just after describe how to change the nodepositionlist implementation in an efficient manner to disallow such misuses - suppose we want to extend the sequence abstract data type with methods indexofelement(eand positionofelement( )which respectively return the index and the position of the (first occurrence ofelement in the sequence show how to implement these methods by expressing them in terms of other methods of the sequence interface - give an adaptation of the array list adt to the deque adt that is different from that given in table - describe the structure and pseudo-code for an array-based implementation of the array list adt that achieves ( time for insertions and removals at index as well as insertions and removals at the end of the array list your implementation should also provide for constant-time get method (hint |
21,005 | given in the previous - describe an efficient way of putting an array list representing deck of cards into random order you may use functionrandominteger( )which returns random number between and inclusive your method should guarantee that every possible ordering is equally likely what is the running time of your methodc- describe method for maintaining favorites list such that every element in has been accessed at least once in the last accesseswhere is the size of your scheme should add only ( additional amortized time to each operation - suppose we have an -element list maintained according to the move-to-front heuristic describe sequence of accesses that is guaranteed to take ohm( time to perform on - design circular node list adt that abstracts circularly linked list in the same way that the node list adt abstracts doubly linked list - describe how to implement an iterator for circularly linked list since hasnext(will always return true in this casedescribe how to perform hasnewnext()which returns true if and only if the next node in the list has not previously had its element returned by this iterator - describe scheme for creating list iterators that fail fastthat isthey all become invalid as soon as the underlying list changes - an array is sparse if most of its entries are null list can be used to implement such an arrayaefficiently in particularfor each nonnull 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 nonnull entries in describe and analyze efficient ways of performing the |
21,006 | entries in by increasing indices or notc- there is simplebut inefficientalgorithmcalled bubble-sortfor sorting sequence of comparable elements this algorithm scans the sequence - timeswherein each scanthe algorithm compares the current element with the next one and swaps them if they are out of order give pseudo-code description of bubble-sort that is as efficient as possible assuming is implemented with doubly linked list what is the running time of this algorithmc- answer exercise - assuming is implemented with an array list - useful operation in databases is the natural join if we view database as list of ordered pairs of objectsthen the natural join of databases and is the list of all ordered triples ( , ,zsuch that the pair ( ,yis in and the pair ( ,zis in describe and analyze an efficient algorithm for computing the natural join of list of pairs and list of pairs - when bob wants to send alice message on the internethe breaks into data packetsnumbers the packets consecutivelyand injects them into the network when the packets arrive at alice' computerthey may be out of orderso alice must assemble the sequence of packets in order before she can be sure she has the entire message describe an efficient scheme for alice to do this what is the running time of this algorithmc- given list of positive integerseach represented with logn describe an ( )-time method for finding -bit integer not in bitsc- argue why any solution to the previous problem must run in ohm(ntime - given list of arbitrary integersdesign an ( )-time method for finding an integer that cannot be formed as the sum of two integers in |
21,007 | isabel has an interesting way of summing up the values in an array of integerswhere is power of two she creates an array of half the size of and sets [ia[ + [ ]for , ( / if has size then she outputs [ otherwiseshe replaces with band repeats the process what is the running time of her algorithmprojects - implement the array list adt by means of an extendable array used in circular fashionso that insertions and deletions at the beginning and end of the array list run in constant time - implement the array list adt using doubly linked list show experimentally that this implementation is worse than the array-based approach - write simple text editorwhich stores and displays string of characters using the list adttogether with cursor object that highlights position in this string your editor should support the following operationsleftmove cursor left one character (do nothing if at text endrightmove cursor right one character (do nothing if at text endcutdelete the character right of the cursor (do nothing at text endpaste cinsert the character just after the cursor - implement phased favorites list phase consists of accesses in the listfor given parameter during phasethe list should maintain itself so that elements are ordered by decreasing access counts during that phase at the end |
21,008 | experimentallydetermine what are the best values of for various list sizes - write complete adapter class that implements the sequence adt using java util arraylist object - implement the favorites list application using an array list instead of list compare it experimentally to the list-based implementation notes the concept of viewing data structures as collections (and other principles of objectoriented designcan be found in object-oriented design books by booch [ ]budd [ ]golberg and robson [ ]and liskov and guttag [ lists and iterators are pervasive concepts in the java collections framework our node list adt is derived from the "positionabstraction introduced by ahohopcroftand ullman [ ]and the list adt of wood [ implementations of lists via arrays and linked lists are discussed by knuth [ |
21,009 | trees contents general trees tree definitions and properties the tree abstract data type |
21,010 | implementing tree tree traversal algorithms depth and height preorder traversal postorder traversal binary trees the binary tree adt binary tree interface in java |
21,011 | properties of binary trees linked structure for binary trees an array-list representation of binary tree traversals of binary trees the template method pattern exercises java datastructures net general trees 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 list trees also provide natural organization for dataand consequently have become ubiquitous structures in file systemsgraphical user interfacesdatabasesweb sitesand other computer systems |
21,012 | 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 "descendentbeing the most common words used to describe relationships we show an example of family tree in figure figure family tree showing some descendents of abrahamas recorded in genesis - 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 treefigure tree with nodes representing the organization of fictitious corporation the root stores |
21,013 | salespurchasingand 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 relationshipthat satisfies the following propertiesif is nonemptyit has special nodecalled the root of tthat 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 doesn' have any nodes this convention also allows us to define tree recursivelysuch that tree is either empty or consists of node rcalled the root of tand (possibly emptyset of trees whose roots are the children of other node relationships |
21,014 | if has no children node is internal if it has one or more children external nodes are also known as leaves example in most operating systemsfiles are organized hierarchically into nested directories (also called folders)which are presented to the user in the form of tree (see figure more specificallythe internal nodes of the tree are associated with directories and the external nodes 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 "figure system tree representing portion of file node is an ancestor of node if or is an ancestor of the parent of converselywe say that node is descendent of node if is an ancestor of for examplein figure cs is an ancestor of papers/and pr is descendent of cs the subtree of rooted at node is the tree consisting of all the descendents of in (including itselfin figure the subtree rooted at cs consists of the nodes cs /gradeshomeworks/programs/hw hw hw pr pr and pr |
21,015 | 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/marketexample the inheritance relation between classes in java program forms tree the rootjava lang objectis an ancestor of all other classes each classcis descendent of this root and is the root of subtree of the classes that extend thusthere is path from to the rootjava lang objectin this inheritance tree ordered trees tree is ordered if there is linear ordering defined for the children of each nodethat iswe can identify the children of node as being the firstsecondthirdand so on such an ordering is usually visualized by arranging siblings left to rightaccording to their ordering ordered trees typically indicate the linear order among siblings by listing them in the correct order example the components of structured documentsuch as bookare hierarchically organized as tree whose internal nodes are partsand sectionsand whose external nodes 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 ordering among the children of each node figure an ordered tree associated with book |
21,016 | the tree adt stores elements at positionswhichas with positions in listare defined relative to neighboring positions the positions in tree are its nodesand neighboring positions satisfy the parent-child relationships that define valid tree thereforewe use the terms "positionand "nodeinterchangeably for trees as with list positiona position object for tree supports the methodelement()return the object stored at this position the real power of node positions in treehowevercomes from the accessor methods of the tree adt that return and accept positionssuch as the followingroot()return the tree' rootan error occurs if the tree is empty parent ( )return the parent of van error occurs if is the root children( )return an iterable collection containing the children of node if tree is orderedthen the iterable collectionchildren( )stores the children of in order if is an external nodethen children(vis empty in addition to the above fundamental accessor methodswe also include the following query methodsisinternal( )test whether node is internal isexternal( )test whether node is external isroot( )test whether node is the root these methods make programming with trees easier and more readablesince we can use them in the conditionals of if statements and while loopsrather than using nonintuitive conditional |
21,017 | not necessarily related to its tree structureincluding the followingsize()return the number of nodes in the tree isempty()test whether the tree has any nodes or not iterator()return an iterator of all the elements stored at nodes of the tree positions()return an iterable collection of all the nodes of the tree replace( , )replace with and return the element stored at node any method that takes position as an argument should generate an error condition if that position is invalid we do not define any specialized update methods for trees here insteadwe prefer to describe different tree update methods in conjunction with specific applications of trees in subsequent in factwe can imagine several kinds of tree update operations beyond those given in this book implementing tree the java interface shown in code fragment represents the tree adt error conditions are handled as followseach method that can take position as an argumentmay throw an invalidpositionexceptionto indicate that the position is invalid method parent throws boundaryviolationexception if it is called on the root method root throws an emptytreeexception if it is called on an empty tree code fragment java interface tree representing the tree adt additional update methods may be addeddepending on the application we do not include such methods in the interfacehowever |
21,018 | natural way to realize tree is to use linked structurewhere we represent each node of by position object (see figure awith the following fieldsa reference to the element stored at va link to the parent of vand some kind of collection (for examplea list or arrayto store links to the children of if is the root of tthen the parent field of is null alsowe store reference to the root of and the number of nodes of in internal variables this structure is schematically illustrated in figure |
21,019 | (athe position object associated with node(bthe 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 node vwe can implement children(vsimply by returning reference to this collection table running times of the methods of an nnode general tree implemented with linked structure we let denote the number of children of node the space usage is (noperation time sizeisempty ( iteratorpositions ( |
21,020 | ( rootparent ( children(vo( isinternalisexternalisroot ( tree traversal algorithms in this sectionwe present algorithms for performing traversal computations on tree by accessing it through the tree adt methods depth and height let be node of tree the depth of is the number of ancestors of vexcluding 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 node 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 node in this method calls itself recursively on the parent of vand adds to the value returned simple java implementation of this algorithm is shown in code fragment code fragment algorithm for computing the depth of node in tree |
21,021 | method depth written in java the running time of algorithm depth(tvis ( )where denotes the depth of the node in the tree tbecause the algorithm performs constant-time recursive step for each ancestor of thusalgorithm depth (tvruns in (nworst-case timewhere is the total number of nodes of tsince node of may have depth in the worst case although such running time is function of the input sizeit is more accurate to characterize the running time in terms of the parameter since this parameter can be much smaller than height the height of node in tree is also defined recursivelyif is an external nodethen the height of is otherwisethe height of is one plus the maximum height of child of 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 depth of an external node of we leave the justification of this fact to an exercise ( - we present here an algorithmheight shown in code fragment and implemented in java in code fragment for computing the height of nonempty tree based on the proposition above and the algorithm depth from code fragment |
21,022 | algorithm height for computing the height of nonempty tree note that this algorithm calls algorithm depth (code fragment code fragment method height written in java note the use of the max method of class java lang math unfortunatelyalgorithm height is not very efficient since height calls algorithm depth (von each external node of tthe running time of height is given by ( ( ))where is the number of nodes of td is the depth of node vand is the set of external nodes of in the worst casethe sums ( is proportional to (see exercise - thusalgorithm height runs in ( time algorithm height shown in code fragment and implemented in java in code fragment computes the height of tree in more efficient manner by using the recursive definition of height |
21,023 | algorithm height for computing the height of the subtree of tree rooted at node code fragment java method height written in algorithm height is more efficient than height (from code fragment the algorithm is recursiveandif it is initially called on the root of tit will eventually be called on each node of thuswe can determine the running time of this method by summingover all the nodesthe amount of time spent at each node (on the nonrecursive partprocessing each node in children(vtakes ( timewhere denotes the number of children of node alsothe while loop has iterations and each iteration of the loop takes ( time plus the time for the recursive call on child of thusalgorithm height spends ( time at each node vand its running time is ( ( )in order to complete the analysiswe make use of the following property proposition let be tree with nodesand let denote the number of children of node of thensumming over the vertices in ts |
21,024 | another nodeand thus contributes one unit to the above sum by proposition the running time of algorithm height when called on the root of tis ( )where is the number of nodes of preorder traversal traversal of tree is systematic way of accessingor "visiting,all the nodes of in this sectionwe present basic traversal scheme for treescalled preorder traversal in the next sectionwe will study another basic traversal schemecalled postorder traversal in preorder traversal of tree tthe 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 specific action associated with the "visitof node depends on the application of this traversaland could involve anything from incrementing counter to performing some complex computation for the pseudo-code for the preorder traversal of the subtree rooted at node is shown in code fragment we initially call this algorithm with preorder( , root()code fragment algorithm preorder for performing the preorder traversal of the subtree of tree rooted at node the preorder traversal algorithm is useful for producing linear ordering of the nodes of tree where parents must always come before their children in the ordering such orderings have several different applications we explore simple instance of such an application in the next example figure preorder traversal of an ordered treewhere the children of each node are ordered from left to right |
21,025 | in example examines an entire document sequentiallyfrom beginning to end if the external nodes are removed before the traversalthen the traversal examines the table of contents of the document (see figure the preorder traversal is also an efficient way to access all the nodes of tree to justify thislet us consider the running time of the preorder traversal of tree with nodes under the assumption that visiting node takes ( time the analysis of the preorder traversal algorithm is actually similar to that of algorithm height (code fragment )given in section at each node vthe nonrecursive part of the preorder traversal algorithm requires time ( )where is the number of children of thusby proposition the overall running time of the preorder traversal of is (nalgorithm tostringpreorder(tv)implemented in java in code fragment performs preorder printing of the subtree of node of tthat isit performs the preorder traversal of the subtree rooted at and prints the element stored at node when the node is visited recall thatfor an ordered tree tmethod children(vreturns an iterable collection that accesses the children of in order code fragment method tostringpreorder(tvthat performs preorder printing of the elements in the subtree of node of |
21,026 | string representation of an entire tree let us assume again that for each element stored in tree tcalling tostring(returns string associated with the parenthetic string representation (tof tree is recursively defined as follows if consists of single node vthen (tv element(tostring(otherwisep(tv element(tostring(( ( ",**"" ( +")"where is the root of and are the subtrees rooted at the children of vwhich are given in order if is an ordered tree note that the above definition of (tis recursive alsowe are using "+here to denote string concatenation the parenthetic representation of the tree of figure is shown in figure figure parenthetic representation of the tree of figure indentationline breaks and spaces have been added for clarity note thattechnically speakingthere are some computations that occur between and after the recursive calls at node' children in the above algorithm we still consider this algorithm to be preorder traversalhoweversince the primary action of printing node' contents occurs prior to the recursive calls the java method parentheticrepresentationshown in code fragment is variation of method tostringpreorder (code fragment it implements the definition given above to output parenthetic string representation of tree as with the method tostringpreorderthe method parentheticrepresentation makes use of the tostring method that is defined for every java object in factwe can view this method as kind of tostring(method for tree objects |
21,027 | algorithm parentheticrepresentation note the use of the operator to concatenate two strings we explore modification to code fragment in exercise - to display tree in fashion more closely matching that given in figure postorder traversal another important tree traversal algorithm is the postorder traversal this 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 it is similar to the preorder traversalhoweverin that we use it to solve particular problem by specializing an action associated with the "visitof node stillas with the preorder traversalif the tree is orderedwe make recursive calls for the children of node according to their specified order pseudo-code for the postorder traversal is given in code fragment code fragment algorithm postorder for performing the postorder traversal of the subtree of tree rooted at node |
21,028 | will visit node after it has visited all the other nodes in the subtree rooted at (see figure figure of figure postorder traversal of the ordered tree the analysis of the running time of postorder traversal is analogous to that of preorder traversal (see section the total time spent in the nonrecursive portions of the algorithm is proportional to the time spent visiting the children of each node in the tree thusa postorder traversal of tree with nodes takes (ntimeassuming that visiting each node takes ( time that isthe postorder traversal runs in linear time as an example of postorder traversalwe show java method tostringpostorder in code fragment which performs postorder traversal of tree this method prints the element stored at node when it is visited code fragment method tostringpostorder(tvthat performs postorder printing of the elements in the subtree of node of the method implicitly calls tostring on elementswhen they are involved in string concatenation operation |
21,029 | compute some property for each node in treebut computing that property for requires that we have already computed that same property for ' children such an application is illustrated in the following example example consider file system tree twhere external nodes represent files and internal nodes represent directories (example suppose we want to compute the disk space used by directorywhich is recursively given by the sum ofthe size of the directory itself the sizes of the files in the directory the space used by the children directories (see figure this computation can be done with apostorder traversal of tree after the subtrees of an internal node have been traversedwe compute the space used by by adding the sizes of the directory itself and of the files contained in to the space used by each internal child of vwhich was computed by the recursive postorder traversals of the children of recursive java method for computing disk space motivated by example java method diskspaceshown in code fragment performs postorder traversal of file-system tree tprinting the name and disk space used by the directory associated with each internal node of when called on the root of tree tdiskspace runs in time ( )where is the number of nodes of tprovided the auxiliary methods name and size take ( time figure the tree of figure representing file systemshowing the name and size of the associated file/directory inside each nodeand the disk space used by the associated directory above each internal node |
21,030 | method diskspace prints the name and disk space used by the directory associated with each internal node of file-system tree this method calls the auxiliary methods name and sizewhich should be defined to return the name and size of the file/directory associated with node other kinds of traversals |
21,031 | nodes of treewe can also imagine other traversals for examplewe could traverse tree so that we visit all the nodes at depth before we visit the nodes at depth consecutively numbering the nodes of tree as we visit them in this traversal is called the level numbering of the nodes of (see section 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 ordering 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 an external node such binary trees are known as decision treesbecause each external node 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 figure advice decision tree providing investment |
21,032 | whose external nodes 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 externalthen 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 for 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 |
21,033 | incidentallywe can also define binary tree in recursive way such that binary tree is either empty or consists ofa node rcalled the root of and storing an element binary treecalled the left subtree of binary treecalled the right subtree of we discuss some of the specialized topics for binary trees below the binary tree adt as an abstract data typea binary tree is specialization of tree that supports three additional accessor methodsleft( )return the left child of van error condition occurs if has no left child right( )return the right child of van error condition occurs if has no right child hasleft( )test whether has left child |
21,034 | test whether has right child 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 binary tree interface in java we model binary tree as an abstract data type that extends the tree adt and adds the three specialized methods for binary tree in code fragment we show the simple java interface we can define using this approach by the waysince binary trees are ordered treesthe iterable collection returned by method children( (inherited from the tree interfacestores the left child of before the right child of code fragment java interface binary tree for the binary tree adt interface binary tree extends interface tree (code fragment 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 |
21,035 | 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 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 with its number of nodes detailed justification of these properties is left as an exercise ( - proposition let be nonempty binary treeand let nn and denote the number of nodesnumber of external nodesnumber of internal nodesand height of trespectively then has the following properties + < < + - <= <= <= <= - log( + )- <= <= - alsoif is properthen has the following properties |
21,036 | + < <= + - + <= <= <= <= - log( < <( )/ relating internal nodes to external nodes in proper binary tree in addition to the binary tree properties abovewe also have the following relationship between the number of internal nodes and external nodes in proper binary tree proposition in nonempty proper binary tree twith external nodes and internal nodeswe have 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 at the endthe externalnode pile will have 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 |
21,037 | 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 can holdas we explore in an exercise ( - trees linked structure for binary as with general treea natural way to realize binary tree is to use linked structurewhere we represent each node of by position object (see figure awith fields providing references to the element stored at and to the position objects associated with the children and parent of if is the root of tthen the parent field of is null if has no left childthen the left field of is null if has no right childthen the right field of is null alsowe store the number of nodes of in variablecalled size we show the linked structure representation of binary tree in figure figure node (aand linked structure (bfor representing binary tree |
21,038 | |
21,039 | binary tree this interfaces extends positionthus inheriting method elementand has additional methods for setting the element stored at the node (setelementand for setting and returning the left child (setleft and getleft)right child (setright and getright)and parent (setparent and getparentof the node class btnode (code fragment implements interface btposition by an object with fields elementleftrightand parentwhichfor node vreference the element at vthe left child of vthe right child of vand the parent of vrespectively code fragment auxiliary class btnode for implementing binary tree nodes |
21,040 | in code fragments we show portions of class linked binary tree that implements the binary tree interface (code fragment using linked data structure this class stores the size of the tree and reference to the btnode object associated with the root of the tree in internal variables in |
21,041 | various other methodsincluding accessor method sibling( )which returns the sibling of node vand the following update methodsaddroot( )create and return new node storing element and make the root of the treean error occurs if the tree is not empty insertleft( , )create and return new node storing element eadd as the the left child of and return wan error occurs if already has left child insertright( , )create and return new node storing element eadd as the the right child of and return zan error occurs if already has right child remove( )remove node vreplace it with its childif anyand return the element stored at van error occurs if has two children attach( , , )attach and respectivelyas the left and right subtrees of the external node van error condition occurs if is not external class linkedbinarytree has constructor with no arguments that returns an empty binary tree starting from this empty treewe can build any binary tree by creating the first node with method addroot and repeatedly applying the insertleft and insertright methods and/or the attach method likewisewe can dismantle any binary tree using the remove operationultimately reducing such tree to an empty binary tree when position is passed as an argument to one of the methods of class linkedbinarytreeits validity is checked by calling an auxiliary helper methodcheckposition(va list of the nodes visited in preorder traversal of the tree is constructed by recursive method preorderpositions error conditions are indicated by throwing exceptions invalid position exceptionboundaryviolation exceptionemptytreeexceptionand nonemptytreeexception code fragment portions of the linked binary tree classwhich implements the binary tree interface (continues in code fragment |
21,042 | binary tree classwhich implements the binary tree interface (continues in code fragment |
21,043 | binary tree classwhich implements the binary tree interface (continues in code fragment |
21,044 | linkedbinarytree classwhich implements the |
21,045 | code fragment portions of the linked binary tree classwhich implements the binary tree interface (continued from code fragment |
21,046 | let us now analyze the running times of the methods of class linked binary treewhich uses linked structure representation |
21,047 | methods size(and isempty(use an instance variable storing the number of nodes of tand each take ( time the accessor methods rootleftrightsibling and parent take ( time method replace( ,etakes ( time methods iterator(and positions(are implemented by performing preorder traversal of the tree (using the auxiliary method preorderpositionsthe nodes visited by the traversal are stored in position list implemented by class nodepositionlist (section and the output iterator is generated with method iterator(of class nodepositionlist methods iterator(and positions(take (ntime and methods hasnext(and next(of the returned iterators run in ( time method children uses similar approach to construct the returned iterable collectionbut it runs in ( timesince there are at most two children for any node in binary tree the update methods insertleftinsertrightattachand remove all run in ( timeas they involve constant-time manipulation of constant number of nodes considering the space required by this data structure for tree with nodesnote that there is an object of class btnode (code fragment for every node of tree thusthe overall space requirement is (ntable summarizes the performance of the linked structure implementation of binary tree table running times for the methods of an nnode binary tree implemented with linked structure methods hasnext(and next(of the iterators returned by iterator()positions(iterator()and children(viterator(run in ( time the space usage is (noperation time sizeisempty ( iteratorpositions |
21,048 | replace ( rootparentchildrenleftrightsibling ( haslefthasrightisinternalisexternalisroot ( insertleftinsertrightattachremove ( an array-list representation of binary tree an alternative representation of binary tree is based on way of numbering the nodes of for every node of tlet (vbe the integer defined as follows if is the root of tthen ( if is the left child of node uthen ( (uif is the right child of node uthen ( ( the numbering function is known as level numbering of the nodes in binary tree tfor it numbers the nodes on each level of in increasing order from left to rightalthough it may skip some numbers (see figure figure binary tree level numbering(ageneral scheme(ban example |
21,049 | means of an array list such that node of is the element of at index (vas mentioned in the previous we realize the array list by means of an extendable array (see section such an implementation is simple and efficientfor we can use it to easily perform the methods rootparentleftrighthaslefthasrightisinternalisexternaland isroot by using simple arithmetic operations on the numbers (vassociated with each node involved in the operation we leave the details of this implementation as an exercise ( - we show an example array-list representation of binary tree in figure figure representation of binary tree by means of an array list |
21,050 | all the nodes of the array list has size pm since the element of at index is not associated with any node of alsos will havein generala number of empty elements that do not refer to existing nodes of in factin the worst casen nthe 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-list representation of binary tree is space efficient stillfor general binary treesthe exponential worst-case space requirement of this representation is prohibitive table summarizes running times of the methods of binary tree implemented with an array list we do not include any tree update methods here table running times for binary tree implemented with an array list we denote the number of nodes of with nand denotes the size of the space usage is ( )which is ( nin the worst case operation |
21,051 | sizeisempty ( iteratorpositions (nreplace ( rootparentchildrenleftright ( haslefthasrightisinternalisexternalisroot ( traversals of binary trees as with general treesbinary tree computations often involve traversals building an expression tree consider the problem of constructing an expression tree from fully parenthesized arithmetic expression of size (recall example and code fragment in code fragment we give algorithm buildexpression for building such an expression treeassuming all arithmetic operations are binary and variables are not parenthesized thusevery parenthesized subexpression contains an operator in the middle the algorithm uses stack while scanning the input expression looking for variablesoperatorsand right parentheses when we see variable or operator xwe create single-node binary tree twhose root stores and we push on the stack when we see right parenthesis")"we pop the top three trees from the stack swhich represent subexpression ( we then attach the trees for and to the one for oand push the resulting tree back on we repeat this until the expression has been processedat which time the top element on the stack is the expression tree for the total running time is ( |
21,052 | buildexpression preorder traversal of binary tree since any binary tree can also be viewed as general treethe preorder traversal for general trees (code fragment can be applied to any binary tree we can simplify the algorithm in the case of binary tree traversalhoweveras we show in code fragment code fragment algorithm binarypreorder for performing the preorder traversal of the subtree of binary tree rooted at node |
21,053 | traversal for binary trees postorder traversal of binary tree analogouslythe postorder traversal for general trees (code fragment can be specialized for binary treesas shown in code fragment code fragment algorithm binarypostorder for performing the postorder traversal of the subtree of binary tree rooted at node expression tree evaluation the postorder traversal of binary tree can be used to solve the expression tree evaluation problem in this problemwe are given an arithmetic expression treethat isa binary tree where each external node has value associated with it and each internal node has an arithmetic operation associated with it (see example )and we want to compute the value of the arithmetic expression represented by the tree algorithm evaluateexpressiongiven in code fragment evaluates the expression associated with the subtree rooted at node of an arithmetic expression tree by performing postorder traversal of starting at in this |
21,054 | that we use the fact that an arithmetic expression tree is proper binary tree code fragment algorithm evaluateexpression for evaluating the expression represented by the subtree of an arithmetic expression tree rooted at node the expression-tree evaluation application of the postorder traversal provides an ( )-time algorithm for evaluating an arithmetic expression represented by binary tree with nodes indeedlike the general postorder traversalthe postorder traversal for binary trees can be applied to other "bottom-upevaluation problems (such as the size computation given in example as well inorder traversal of binary tree an additional traversal method for binary tree is the inorder traversal in this traversalwe visit node between the recursive traversals of its left and right subtrees the inorder traversal of the subtree rooted at node in binary tree is given in code fragment code fragment algorithm inorder for performing the inorder traversal of the subtree of binary tree rooted at node |
21,055 | nodes of "from left to right indeedfor every node vthe inorder traversal visits after all the nodes in the left subtree of and before all the nodes in the right subtree of (see figure figure inorder traversal of binary tree binary search trees let be set whose elements have an order relation for examples could be set of integers binary search tree for is proper binary tree such that each internal node of stores an element of sdenoted with (vfor each internal node of tthe elements stored in the left subtree of are less than or equal to (vand the elements stored in the right subtree of are greater than or equal to (vthe external nodes of do not store any element an inorder traversal of the internal nodes of binary search tree visits the elements in nondecreasing order (see figure |
21,056 | the blue solid path is traversed when searching (successfullyfor the blue 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 tstarting at the root (see figure at each internal node encounteredwe compare our search value with the element (vstored 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 external nodethe 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 indeedit is exactly this correspondence to binary decision tree that motivates restricting binary search trees to be proper binary trees (with "place-holderexternal nodesnote that the running time of searching in binary search tree is proportional to the height of recall from proposition that the height of proper 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 we illustrate an example search operation in binary search tree in figure and we study binary search trees in more detail in section using inorder traversal for tree drawing |
21,057 | of binary tree we can draw binary tree with an algorithm that assigns xand -coordinates to node of using the following two rules (see figure ) (vis the number of nodes visited before in the inorder traversal of (vis the depth of in in this applicationwe take the convention common in computer graphics that xcoordinates increase left to right and -coordinates increase top to bottom so the origin is in the upper left corner of the computer screen figure an inorder drawing of binary tree the euler tour traversal of binary tree the tree-traversal algorithms we have discussed so far are all forms of iterators each traversal visits the nodes of tree in certain orderand is guaranteed to visit each node exactly once we can unify the tree-traversal algorithms given above into single frameworkhoweverby relaxing the requirement that each node be visited exactly once the resulting traversal method is called the euler tour traversalwhich we study next the advantage of this traversal is that it allows for more general kinds of algorithms to be expressed easily the euler tour traversal of binary tree can be informally defined as "walkaround twhere we start by going from the root toward its left childviewing the edges of as being "wallsthat we always keep to our left (see figure each node of is encountered three times by the euler tour"on the left(before the euler tour of ' left subtree"from below(between the euler tours of ' two subtrees"on the right(after the euler tour of ' right subtree |
21,058 | describe the euler tour of the subtree rooted at in code fragment figure euler tour traversal of binary tree code fragment the euler tour of the subtree of binary tree rooted at the running time of the euler tour traversal of an -node tree is easy to analyzeassuming each visit action takes ( time since we spend constant amount of time at each node of the tree during the traversalthe overall running time is (nthe preorder traversal of binary tree is equivalent to an euler tour traversal such that each node has an associated "visitaction occur only when it is encountered on the left likewisethe inorder and postorder traversals of binary tree are equivalent to an euler tour such that each node has an associated "visitaction occur only when it is encountered from below or on the rightrespectively the euler tour traversal extends the preorderinorderand postorder traversalsbut it can also perform other kinds of traversals for examplesuppose we wish to compute the number of descendents of each node in an -node binary tree we |
21,059 | each time we visit node on the left to determine the number of descendents of node vwe compute the difference between the values of the counter when is visited on the left and when it is visited on the rightand add this simple rule gives us the number of descendents of vbecause each node in the subtree rooted at is counted between ' visit on the left and ' visit on the right thereforewe have an ( )-time method for computing the number of descendents of each node another application of the euler tour traversal is to print fully parenthesized arithmetic expression from its expression tree (example algorithm printexpressionshown in code fragment accomplishes this task by performing the following actions in an euler tour"on the leftactionif the node is internalprint "("from belowactionprint the value or operator stored at the node "on the rightactionif the node is internalprint ")code fragment an algorithm for printing the arithmetic expression associated with the subtree of an arithmetic expression tree rooted at the template method pattern |
21,060 | 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 following the template method patternwe design an algorithm that implements generic euler tour traversal of binary tree this algorithmcalled templateeulertouris shown in code fragment code fragment an euler tour traversal of the subtree of binary tree rooted at node vfollowing the template method pattern when called on node vmethod templateeulertour calls several other auxiliary methods at different phases of the traversal namelyit creates local variable of type tourresultwhich is used to store intermediate results of the computation and has fields leftright and out calls auxiliary method visitleft( , , )which performs the computations associated with encountering the node on the left if has left childrecursively calls itself on the left child of and stores the returned value in left calls auxiliary method visitbelow(tvr)which performs the computations associated with encountering the node from below if has right childrecursively calls itself on the right child and stores the returned value in right |
21,061 | calls auxiliary method visitright(tvr)which performs the computations associated with encountering the node on the right returns out method templateeulertour can be viewed as template or "skeletonof an euler tour (see code fragment java implementation java class eulertourshown in code fragment implements an euler tour traversal using the template method pattern the recursive traversal is performed by method eulertour the auxiliary methods called by eulertour are empty place holders that isthey have an empty body or they just return null class eulertour is abstract and thus cannot be instantiated it contains an abstract methodcalled executewhich needs to be specified in the concrete subclass of eulertour class tourresultwith fields leftrightand outis not shown code fragment java class eulertour defining generic euler tour of binary tree this class realizes the template method pattern and must be specialized in order to get an interesting computation |
21,062 | neverthelesswe can extend it and override the empty auxiliary methods to do useful tasks we illustrate this concept using arithmetic expression trees (see example we assume that an arithmetic expression tree has objects of type |
21,063 | expressionvariable (for variablesand expressionoperator (for operatorsin turnclass expressionoperator has subclasses for the arithmetic operatorssuch as additionoperator and multiplicationoperator method value of expressionterm is overridden by its subclasses for variableit returns the value of the variable for an operatorit returns the result of applying the operator to its operands the operands of an operator are set by method setoperands of expressionoperator in code fragment we show the classes expressiontermexpressionvariableexpressionoperator and additionoperator code fragment classes for variablegeneric operatorand addition operator of an arithmetic expression |
21,064 | evaluateexpressiontour and printexpressiontourspecializing eulertourthat evaluate and print the arithmetic expression stored in binary treerespectively class evaluateexpressiontour overrides auxiliary method visitright(tvrwith the following computationif is an external nodeset out equal to the value of the variable stored at else ( is an internal node)combine left and right with the operator stored at vand set out equal to the result of the operation class printexpressiontour overrides methods visitleftvisitbelowand visitright following the approach of pseudo-code version shown in code fragment |
21,065 | that specializes eulertour to evaluate the expression associated with an arithmetic expression tree code fragment class printexpressiontour that specializes eulertour to print the expression associated with an arithmetic expression tree exercises |
21,066 | java datastructures net reinforcement - the following questions refer to the tree of figure which node is the rootb what are the internal nodesc how many descendents does node cs haved how many ancestors does node cs havee what are the siblings of node homeworks/ which nodes are in the subtree rooted at node projects/ what is the depth of node papers/ what is the height of the treer- find the value of the arithmetic expression associated with each subtree of the binary tree of figure - |
21,067 | by means of proper binary tree with (nnodes - what are the minimum and maximum number of internal and external nodes in an improper binary tree with nodesr- show tree achieving the worst-case running time for algorithm depth - give justification of proposition - what is the running time of algorithm height (tv(code fragment when called on node distinct from the root of tr- let be the tree of figure and refer to code fragments and give the output of tostringpostorder(tt root() give the output of parentheticrepresentation(tt root() - describe modification to parentheticrepresentationfrom code fragment so that it uses the length(method for string objects to output the parenthetic representation of tree with line breaks and spaces added to display the tree in text window that is characters wide - draw an arithmetic expression tree that has four external nodesstoring the numbers and (with each number stored in distinct external nodebut not necessarily in this order)and has three internal nodeseach storing an operator from the set /}so that the value of the root is the operators may return and act on fractionsand an operator may be used more than once |
21,068 | let be an ordered tree with more than one node is it possible that the preorder traversal of visits the nodes in the same order as the postorder traversal of tif sogive an exampleotherwiseargue why this cannot occur likewiseis it possible that the preorder traversal of visits the nodes in the reverse order of the postorder traversal of tif sogive an exampleotherwiseargue why this cannot occur - answer the previous question for the case when is proper binary tree with more than one node - what is the running time of parentheticrepresentation(tt root()(code fragment for tree with nodesr- draw (singlebinary tree such that each internal node of stores single character preorder traversal of yields examfun an inorder traversal of yields mafxuen - answer the following questions so as to justify proposition what is the minimum number of external nodes for proper binary tree with height hjustify your answer what is the maximum number of external nodes for proper binary tree with height hjustify your answer |
21,069 | let be proper binary tree with height and nodes show that log( - < <( )/ for which values of and can the above lower and upper bounds on be attained with equalityr- describe generalization of the euler tour traversal to trees such that each internal node has three children describe how you could use this traversal to compute the height of each node in such tree - compute the output of algorithm tostringpostorder( , root())from code fragment on the tree of figure - illustrate the execution of algorithm diskspace(tt root()(code fragment on the tree of figure - let be the binary tree of figure give the output of tostringpostorder(tt root()(code fragment give the output of parentheticrepresentation(tt root()(code fragment - let be the binary tree of figure give the output of tostringpostorder(tt root()(code fragment |
21,070 | give the output of printexpression(tt root()(code fragment - describein pseudo-codean algorithm for computing the number of descendents of each node of binary tree the algorithm should be based on the euler tour traversal - let be (possibly improperbinary tree with nodesand let be the sum of the depths of all the external nodes of show that if has the minimum number of external nodes possiblethen is (nand if has the maximum number of external nodes possiblethen is ( log nr- let be binary tree with nodesand let be the level numbering of the nodes of tas given in section show thatfor every node of tp( < show an example of binary tree with seven nodes that attains the above upper bound on (vfor some node - show how to use the euler tour traversal to compute the level numberdefined in section of each node in binary tree - draw the binary tree representation of the following arithmetic expression"((( ( ))/(( (( ) ) - let be binary tree with nodes that is realized with an array listsand let be the level numbering of the nodes in tas given in section give pseudo-code descriptions of each of the methods rootparentleftrighthaslefthasrightisinternalisexternaland isroot |
21,071 | - for each node in tree tlet pre(vbe the rank of in preorder traversal of tlet post(vbe the rank of in postorder traversal of tlet depth (vbe the depth of vand let desc(vbe the number of descendents of vnot counting itself derive formula defining post(vin terms of desc( )depth( )and pre( )for each node in - let be tree whose nodes store strings give an efficient algorithm that computes and printsfor every node of tthe string stored at and the height of the subtree rooted at - design algorithms for the following operations for binary tree tpreordernext( )return the node visited after node in preorder traversal of inordernext( )return the node visited after node in an inorder traversal of postordernext( )return the node visited after node in postorder traversal of what are the worst-case running times of your algorithmsc- give an ( )-time algorithm for computing the depth of all the nodes of tree twhere is the number of nodes of - the indented parenthetic representation of tree is variation of the parenthetic representation of (see figure that uses indentation and line breaks as illustrated in figure give an algorithm that prints this representation of tree |
21,072 | representation of - let be (possibly improperbinary tree with nodesand let be the sum of the depths of all the external nodes of describe configuration for such that is ohm( such tree would be the worst case for the asymptotic running time of algorithm height (code fragment - for tree tlet denote the number of its internal nodesand let denote the number of its external nodes show that if every internal node in has exactly childrenthen - describe how to clone proper binary tree using the attach method instead of methods insertleft and insertright - the balance factor of an internal node of proper binary tree is the difference between the heights of the right and left subtrees of show how to specialize the euler tour traversal of section to print the balance factors of all the internal nodes of proper binary tree |
21,073 | two ordered trees and 'are said to be isomorphic if one of the following holdsboth and 'are empty both and 'consist of single node both and 'have the same number > of subtreesand the ith subtree of is isomorphic to the ith subtree of ''for , design an algorithm that tests whether two given ordered trees are isomorphic what is the running time of your algorithmc- extend the concept of an euler tour to an ordered tree that is not necessarily binary tree - we can define binary tree representation for an ordered general tree as follows (see figure )for each node of tthere is an internal node of associated with if is an external node of and does not have sibling immediately following itthen the children of in are external nodes if is an internal node of and is the first child of in tthen is the left child of in if node has sibling immediately following itthen is the right child of in given such representation of general ordered tree tanswer each of the following questionsa is preorder traversal of equivalent to preorder traversal of tb is postorder traversal of equivalent to postorder traversal of tc is an inorder traversal of equivalent to one of the standard traversals of tif sowhich one |
21,074 | tree(atree (bbinary tree for the dashed edges connect nodes of that are siblings in - as mentioned in exercise - ,postfix notation is an unambiguous way of writing an arithmetic expression without parentheses it is defined so that if "(exp )op(exp )is normal (infixfully parenthesized expression with operation opthen its postfix equivalent is "pexp pexp op"where pexp is the postfix version of exp and pexp is the postfix version of exp the postfix version of single number of variables is just that number or variable sofor examplethe postfix version of the infix expression "(( ( ))/ is " /give an efficient algorithm for converting an infix arithmetic expression to its equivalent postfix notation (hintfirst convert the infix expression into its equivalent binary tree representationusing the algorithm of code fragment - given proper binary tree tdefine the reflection of to be the binary tree such that each node in is also in 'but the left child of in is ' right child in and the right child of in is ' left child in show that preorder traversal of proper binary tree is the same as the postorder traversal of ' reflectionbut in reverse order - algorithm preorderdraw draws binary tree by assigning xand ycoordinates to each node such that (vis the number of nodes preceding in the preorder traversal of and (vis the depth of in algorithm |
21,075 | using postorder traversal show that the drawing of produced by preorderdraw has no pairs of crossing edges redraw the binary tree of figure using preorderdraw show that the drawing of produced by postorderdraw has no pairs of crossing edges redraw the binary tree of figure using postorderdraw - design an algorithm for drawing general trees that generalizes the inorder traversal approach for drawing binary trees - let visit action in the euler tour traversal be denoted by pair ( , )where is the visited node and is one of leftbelowor right design and analyze an algorithm for performing operation tournext(va)which returns the visit action ( ,bfollowing ( ,ac- consider variation of the linked data structure for binary trees where each node object has references to the node objects of the children but not to the node object of the parent describe an implementation of the methods of binary tree with this data structure and analyze the time complexity for these methods - design an alternative implementation of the linked data structure for proper binary trees using class for nodes that specializes into subclasses for an internal nodean external nodeand the root node - within the linked data structure for binary treesexplore an alternative design for implementing the iterators returned by the methods iterator()positions(iterator()and children(viterator(such that each of these methods takes ( time can you still achieve constant time implementations for the methods hasnext(and next(of the iterators returnedc- |
21,076 | between two nodes and as the lowest node in that has both and as descendents (where we allow node to be descendent of itselfgiven two nodes and wdescribe an efficient algorithm for finding the lca of and what is the running time of your algorithmc- let be binary tree with nodesandfor any node in tlet denote the depth of in the distance between two nodes and in is where is the lowest common ancestor (lcau of and the diameter of is the maximum distance between two nodes in describe an efficient algorithm for finding the diameter of what is the running time of your algorithmc- suppose each node of binary tree is labeled with its value (vin level numbering of design fast method for determining (ufor the lowest common ancestor (lca)uof two nodes and in tgiven (vand (wyou do not need to find node ujust compute its level-numbering label - justify the bounds in table by providing detailed analysis of the running times of the methods of binary tree implemented with an array listswhere is realized by means of an array - justify table summarizing the running time of the methods of tree represented with linked structureby providingfor each methoda description of its implementationand an analysis of its running time - describe nonrecursive method for evaluating binary tree representing an arithmetic expression - let be binary tree with nodes define roman node to be node in tsuch that the number of descendents in ' left subtree differ from the number of descendents in ' right subtree by at most describe linear-time method for finding each node of tsuch that is not roman nodebut all of ' descendents are roman nodes - |
21,077 | binary tree that runs in linear time and does not use stack - describein pseudo-codea nonrecursive method for performing an in-order traversal of binary tree in linear time - let be binary tree with nodes ( may be realized with an array list or linked structuregive linear-time algorithm that uses the methods of the binary tree interface to traverse the nodes of by increasing values of the level numbering function given in section this traversal is known as the level order traversal - the path length of tree is the sum of the depths of all the nodes in describe linear-time method for computing the path length of tree (which is not necessarily binaryc- define the internal path lengthi( )of tree to be the sum of the depths of all the internal nodes in likewisedefine the external path lengthe( )of tree to be the sum of the depths of all the external nodes in show that if is proper binary tree with nodesthen (ti(tn projects - implement the binary tree adt using an array list - implement the tree adt using linked structure - write program that draws binary tree - write program that draws general tree - |
21,078 | - implement the tree adt using the binary tree representation described in exercise - you may reuse the linkedbinarytree implementation of binary tree - slicing floorplan divides rectangle with horizontal and vertical sides using horizontal and vertical cuts (see figure slicing floorplan can be represented by proper binary treecalled slicing treewhose internal nodes represent the cutsand whose external nodes represent the basic rectangles into which the floorplan is decomposed by the cuts (see figure the compaction problem for slicing floorplan is defined as follows assume that each basic rectangle of slicing floorplan is assigned minimum width and minimum height the compaction problem is to find the smallest possible height and width for each rectangle of the slicing floorplan that is compatible with the minimum dimensions of the basic rectangles namelythis problem requires the assignment of values (vand (vto each node of the slicing tree such thatdesign data structure for slicing floorplans that supports the operationscreate floorplan consisting of single basic rectangle decompose basic rectangle by means of horizontal cut decompose basic rectangle by means of vertical cut assign minimum height and width to basic rectangle draw the slicing tree associated with the floorplan compact and draw the floorplan figure (aslicing floorplan(bslicing tree associated with the floorplan |
21,079 | write program that can play tic-tac-toe effectively (see section to do thisyou will need to create game tree twhich is tree where each node corresponds to game configurationwhichin this caseis representation of the tic-tac-toe board the root node corresponds to the initial configuration for each internal node in tthe children of correspond to the game states we can reach from ' game state in single legal move for the appropriate playera (the first playeror (the second playernodes at even depths correspond to moves for and nodes at odd depths correspond to moves for external nodes are either final game states or are at depth beyond which we don' want to explore we score each external node with value that indicates how good this state is for player in large gameslike chesswe have to use heuristic scoring functionbut for small gameslike tic-tac-toewe can construct the entire game tree and score external nodes as indicating whether player has windrawor lose in that configuration good algorithm for choosing moves is minimax in this algorithmwe assign score to each internal node in tsuch that if represents ' turnwe compute ' score as the maximum of the scores of ' children (which corresponds to ' optimal play from vif an internal node represents ' turnthen we compute ' score as the minimum of the scores of ' children (which corresponds to ' optimal play from vp- write program that takes as input fully parenthesizedarithmetic expression and converts it to binary expression tree your program should display the tree in some way and also print the value associated with the root for an additional challengeallow for the leaves to store variables of the form and so onwhich are initially and which can be updated interactively by your programwith the corresponding update in the printed value of the root of the expression tree |
21,080 | write program that visualizes an euler tour traversal of proper binary treeincluding the movements from node to node and the actions associated with visits on the leftfrom belowand on the right illustrate your program by having it compute and display preorder labelsinorder labelspostorder labelsancestor countsand descendent counts for each node in the tree (not necessarily all at the same timep- the arithmetic expression code shown in code fragments only work for integer expressions with the addition operator write java program that can evaluation arbitrary expressions of any number type of object notes discussions of the classic preorderinorderand postorder tree traversal methods can be found in knuth' fundamental algorithms book [ the euler tour traversal technique comes from the parallel algorithms communityas it is introduced by tarjan and vishkin [ and is discussed by 'aj' [ and by karp and ramachandran [ the algorithm for drawing tree is generally considered to be part of the "folkloreof graph drawing algorithms the reader interested in graph drawing is referred to works by tamassia [ and di battista et al [ the puzzler in exercise - was communicated by micha sharir |
21,081 | priority queues contents the priority queue abstract data type keysprioritiesand total order relations |
21,082 | the priority queue adt sorting with priority queue implementing priority queue with list implementation with an unsorted list implementation with sorted list selection-sort and insertion-sort heaps |
21,083 | complete binary trees and their representation implementing priority queue with heap java heap implementation heap-sort bottom-up heap construction adaptable priority queues methods of the adaptable priority queue adt |
21,084 | implementing an adaptable priority queue exercises java datastructures net the priority queue abstract data type priority queue is an abstract data type for storing collection of prioritized elements that supports arbitrary element insertion but supports removal of elements in order of prioritythat isthe element with first priority can be removed at any time this adt is fundamentally different from the position-based data structures we discussed in previous such as stacksqueuesdequeslistsand even trees these other data structures store elements at specific positionswhich are often positions in linear arrangement of the elements determined by the insertion and deletion operations performed the priority queue adt stores elements according to their prioritiesand exposes no notion of "positionto the user keysprioritiesand total order relations applications commonly require that we compare objects according to parameters or propertiescalled "keys,that are assigned for each object in collection formallywe define key to be an object that is assigned to an element as specific attribute for that elementwhich can be used to identify or weigh that element note that the key is assigned to an elementtypically by user or applicationhencea key might represent property that an element did not originally possess the key an application assigns to an element is not necessarily uniquehoweverand an application may even change an element' key if it needs to for examplewe can compare companies by earnings or by number of employeeshenceeither of these parameters can be used as key for companydepending on the information we wish to extract likewisewe can compare restaurants by critic' food quality rating or by average entree price to achieve the most generality thenwe allow key to be of any type that is appropriate for particular application |
21,085 | more than single numerical valuesuch as pricelengthweightor speed that isa key can sometimes be more complex property that cannot be quantified with single number for examplethe priority of standby passengers is usually determined by taking into account host of different factorsincluding frequentflyer statusthe fare paidand check-in time in some applicationsthe key for an object is part of the object itself (for exampleit might be an instance variable storing the list price of bookor the weight of carin other applicationsthe key is not part of the object but the object gets assigned its key by the application (for examplethe quality rating given to stock by financial analystor the priority assigned to standby passenger by gate agentcomparing keys with total orders priority queue needs comparison rule that will never contradict itself in order for comparison rulewhich we denote by <=to be robust in this wayit must define total order relationwhich is to say that the comparison rule is defined for every pair of keys and it must satisfy the following propertiesreflexive propertyk < antisymmetric propertyif < and < then transitive propertyif < and < then < any comparison rule<=that satisfies these three properties will never lead to comparison contradiction in factsuch rule defines linear ordering relationship among set of keyshenceif (finitecollection of elements has total order defined for itthen the notion of smallest keyk min is well definedas key in which min <kfor any other key in our collection priority queue is collection of elementscalled valueseach having an associated key that is provided at the time the element is inserted key-value pair inserted into priority queue is called an entry of the priority queue the name "priority queuecomes from the fact that keys determine the "priorityused to pick entries to be removed the two fundamental methods of priority queue are as followsinsert( , )insert value with key into removemin()return and remove from an entry with the smallest keythat isan entry whose key is less than or equal to that of every other entry in by the waysome people refer to the removemin method as the "extractminmethodso as to stress that this method simultaneously removes and returns an entry there are many applications where the insert and |
21,086 | in the example that follows example suppose certain flight is fully booked an hour prior to departure because of the possibility of cancellationsthe airline maintains priority queue of standby passengers hoping to get seat the priority of each standby passenger is determined by the airline taking into account the fare paidthe frequent-flyer statusand the time that the passenger is inserted into the priority queue standby passenger reference is inserted into the priority queue with an insert operation as soon as he or she requests to fly standby shortly before the flight departureif seats become available (for exampledue to noshows or last-minute cancellations)the airline removes standby passenger with first priority from the priority queueusing aremovemin operation and lets this person board this process is then repeated until all available seats have been filled or the priority queue becomes empty entries and comparators there are still two important issues that we have left undetermined to this pointhow do we keep track of the associations between keys and valueshow do we compare keys so as to determine smallest keyanswering these questions involves the use of two interesting design patterns the definition of priority queue implicitly makes use of two special kinds of objects that answer the above questionsthe entry and comparatorwhich we discuss in this subsection entries an entry is an association between key and value xthat isan entry is simply key-value pair we use entries in priority queue to keep track of the way is associating keys and their corresponding values an entry is actually an example of more general object-oriented design patternthe composition patternwhich defines single object that is composed of other objects we use this pattern in priority queue when we define the entries being stored in the priority queue to be pairs consisting of key and value pair is the simplest compositionfor it combines two objects into single pair object to implement this conceptwe define class that stores two objects in its first and second instance variablesrespectivelyand provides methods to access and update these variables in code fragment we show an implementation of the composition pattern for entries storing key-value pairs in priority queue we realize this composition with an interface called entry (the java util |
21,087 | compositions include tripleswhich store three objectsquadrupleswhich store four objectsand so on code fragment java interface for an entry storing key-value pairs in priority queue comparators another important issue in the priority queue adt that we need to define is how to specify the total order relation for comparing keys we have number of design choices concerning how to compare keys that we can make at this point one possibilityand the one that is the most concreteis to implement different priority queue for each key type we want to use and each possible way of comparing keys of such types the problem with this approach is that it is not very general and it requires that we create lot of similar code an alternative strategy is to require that keys be able to compare themselves to one another this solution allows us to write general priority queue class that can store instances of key class that implements some kind of comparable interface and encapsulates all the usual comparison methods this solution is an improvement over the specialized approachfor it allows us to write single priority queue class that can handle lots of different types of keys but there are contexts in which this solution is asking too much of the keysas keys often do not "knowhow they ought to be compared two examples follow example given keys and we have that < if the keys are integer objects (to be compared in the usual manner)but < if the keys are string objects (to be compared lexicographicallyexample geometric algorithm may compare points and in the planeby their -coordinate (that isp <= ifx( < ( ))to sort them from left to rightwhile another algorithm may compare them by their -coordinate (that isp < ify( < ( ))to sort them from bottom to top in principlethere is nothing pertaining to the concept of point that says whether points should be compared |
21,088 | (for examplewe can compare the distances of and from the originthusfor the most general and reusable form of priority queuewe should not rely on the keys to provide their comparison rules insteadwe use special comparator objects that are external to the keys to supply the comparison rules comparator is an object that compares two keys we assume that priority queue is given comparator when is constructedand we might also imagine the ability of priority queue to be given new comparator if its old one ever becomes "out of date when needs to compare two keysit uses the comparator it was given to perform the comparison thusa programmer can write general priority queue implementation that works correctly in wide variety of contexts the comparator adt formallythe comparator adt provides streamlined comparison mechanismbased on single method that takes two keys and compares them (or reports an error if the keys are incomparable)compare( , ):returns an integer such that if bi if band if ban error occurs if and cannot be compared the standard java interface java util comparator corresponds to the comparator adt abovewhich offers generaldynamic reusable way to compare objects it also includes an equals(method for comparing comparator to other comparators in code fragment we provide an example of comparatorfor two-dimensional points (code fragment )which is also an example of the composition pattern code fragment comparator for twodimensional points based on the lexicographic order |
21,089 | class representing points in the plane with integer coordinates the priority queue adt having described the composition and comparator patternslet us now define the priority queue adtto support the following method for priority queue psize()return the number of entries in isempty()test whether is empty min()return (but do not removean entry of with smallest keyan error condition occurs if is empty insert( , )insert into key with value and return the entry storing theman error condition occurs if is invalid (that isk cannot be compared with other keys removemin()remove from and return an entry with smallest keyan error condition occurs if is empty |
21,090 | and removemin operations the other methods are query operation min and the generic collection operations size and isempty note that we allow priority queue to have multiple entries with the same key java priority queue interface java interfacecalled priorityqueuefor the priority queue adt is shown in code fragment code fragment queue adt java interface for the priority it should now be obvious that the priority queue adt is much simpler than the sequence adt this simplicity is due to the fact that elements in priority queue are inserted and removed based entirely on their keyswhereas elements are inserted and removed in sequence based on their positions and indices example the following table shows series of operations and their effects on an initially empty priority queue we denote with an entry object returned by method insert the "priority queuecolumn is somewhat deceiving since it shows the entries sorted by key this is more than is required of apriority queue operation output priority queue |
21,091 | [=( , ){( , )insert( ,ce [=( , ){( , ),( , )insert( ,be [=( , ){( , ),( , ),( , )insert( ,de [=( , ){( , ),( , ),( , ),( , )min( {( , ),( , ),( , ),( , )removemin( {( , ),( , ),( , )size( {( , ),( , ),( , )removemin( {( , ),( , )removemin( |
21,092 | {( , )removemin( {the java util priorityqueue class there is no priority queue interface built into javabut java does include classjava util priorityqueuewhich implements the java util queue interface instead of adding and removing elements according to the fifo policyhoweverwhich is the standard queue policythe java util priorityqueue class processes its entries according to priority this priority is defined by given comparator objectwhich is passed to the queue in constructoror it is defined by the natural ordering of the elements being stored in the queue even though the java util priorityqueue is based on the java util queue interfacewe can define simple correspondence between the methods of this class and our priority queue adtas shown in table assuming we have classpqentrywhich implements the entry interface table methods of our priority queue adt and corresponding methods of class java util priorityqueue we assume that the comparator for pqentry objects is essentially the same as the comparator for the keys of the priority queue note that java util priorityqueue has pair of methods for its main operation the two methods have similar functionalitywith minor differences in the way they deal with boundary conditions ( trying to remove from an empty priority queuepriority queue adt classjava util priorityqueue |
21,093 | size(isempty(isempty(insert( ,voffer(new pqentry( , )or add(new pqentry( , )min(peek()or element(removemin(poll()or remove(sorting with priority queue another important application of priority queue is sortingwhere we are given collection of elements that can be compared according to total order relationand we want to rearrange them in increasing order (or at least in nondecreasing order if there are tiesthe algorithm for sorting with priority queue qcalled priorityqueuesortis quite simple and consists of the following two phases in the first phasewe put the elements of into an initially empty priority queue by means of series of insert operationsone for each element in the second phasewe extract the elements from in nondecreasing order by means of series of nremovemin operationsputting them back into in order we give pseudo-code for this algorithm in code fragment assuming that is sequence (pseudo-code for different type of collectionsuch as an array list or node listwould be similarthe algorithm works correctly for any priority queue pno matter how is implemented howeverthe running time of the algorithm is determined by the running times of operations insert and removeminwhich do depend on how is implemented indeedpriorityqueuesort should be considered more sorting "schemethan sorting "algorithm,because it does not specify how the priority queue is implemented the priorityqueuesort scheme is the paradigm of several popular sorting algorithmsincluding selectionsortinsertion-sortand heap-sortwhich we discuss in this |
21,094 | algorithm priorityqueuesort note that the elements of the input sequence serve as keys of the priority queue implementing priority queue with list in this sectionwe show how to implement priority queue by storing its entries in list (see we provide two realizationsdepending on whether or not we keep the entries in sorted by key when analyzing the running time of the methods of priority queue implemented with listwe will assume that comparison of two keys takes ( time implementation with an unsorted list as our first implementation of priority queue plet us consider storing the entries of in list swhere is implemented with doubly linked list thusthe elements of are entries ( , )where is the key and is the value fast insertions and slow removals simple way of performing operation insert( ,xon is to create new entry object ( ,xand add it at the end of list sby executing method addlast(eon this implementation of method insert takes ( time the above insertion algorithm implies that will be unsortedfor always inserting entries at the end of does not take into account the ordering of the keys as consequenceto perform operation min or removemin on pwe must inspect all the elements of list to find an entry (kxof with minimum thusmethods min and removemin take (ntime eachwhere is the number of entries in |
21,095 | proportional to even in the best casesince they each require searching the entire list to find minimum-key entry that isusing the notation of section we can say that these methods run in th(ntime finallywe implement methods size and isempty by simply returning the output of the corresponding methods executed on list thusby using an unsorted list to implement priority queuewe achieve constant-time insertionbut linear-time search and removal implementation with sorted list an alternative implementation of priority queue also uses list sexcept that this time let us store the entries sorted by key specificallywe represent the priority queue by using list of entries sorted by nondecreasing keyswhich means that the first element of is an entry with the smallest key fast removals and slow insertions we can implement method min in this case simply by accessing the first element of the list with the first method of likewisewe can implement the removemin method of as remove( first()assuming that is implemented with doubly linked listoperations min and removemin in take ( time thususing sorted list allows for simple and fast implementations of priority queue access and removal methods this benefit comes at costhoweverfor now method insert of requires that we scan through the list to find the appropriate position to insert the new entry thusimplementing the insert method of now takes (ntimewhere is the number of entries in at the time the method is executed in summarywhen using sorted list to implement priority queueinsertion runs in linear time whereas finding and removing the minimum can be done in constant time comparing the two list-based implementations table compares the running times of the methods of priority queue realized by means of sorted and unsorted listrespectively we see an interesting tradeoff when we use list to implement the priority queue adt an unsorted list allows for fast insertions but slow queries and deletionswhile sorted list allows for fast queries and deletionsbut slow insertions table worst-case running times of the methods of priority queue of size nrealized by |
21,096 | assume that the list is implemented by doubly linked list the space requirement is (nmethod unsorted list sorted list sizeisempty ( ( insert ( (nminremovemin (no( java implementation in code fragments and we show java implementation of priority queue based on sorted node list this implementation uses nested classcalled myentryto implement the entry interface (see section we do not show auxiliary method checkkey( )which throws an invalidkeyexception if key cannot be compared with the comparator of the priority queue class defaultcomparatorwhich realizes comparator using the natural orderingis shown in code fragment code fragment portions of the java class sortedlistpriorityqueuewhich implements the priorityqueue interface the nested class myentry implements the entry interface (continues in code fragment |
21,097 | java class defaultcomparator that implements comparator using the natural ordering and is the default comparator for class sortedlistpriorityqueue |
21,098 | portions of the java class sortedlistpriorityqueuewhich implements the priorityqueue interface (continued from code fragment |
21,099 | recall the priorityqueuesort scheme introduced in section we are given an unsorted sequence containing elementswhich we sort using priority queue in two phases in phase we insert all the elements into and in phase we repeatedly remove the elements from using the removemin(method selection-sort if we implement with an unsorted listthen phase of priorityqueuesort takes (ntimefor we can insert each element in ( time in phase the running time of each removemin operation is proportional to the size of thusthe bottleneck computation is the repeated "selectionof the minimum element in phase for this reasonthis algorithm is better known as selectionsort (see figure as noted abovethe bottleneck is in phase where we repeatedly remove an entry with smallest key from the priority queue the size of starts at and incrementally decreases with each removemin until it becomes thusthe first removemin operation takes time ( )the second one takes time ( )and so onuntil the last (nthoperation takes time ( thereforethe total time needed for the second phase is by proposition we have ( )as does the entire selection-sort algorithm thusphase takes time figure execution of selection-sort on sequence ( , , , , , , |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.