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 i...
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 t...
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 in...
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 i...
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 metho...
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 d...
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 a...
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 ...
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 imp...
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 str...
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 nodeca...
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 ...
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 tre...
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 li...
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(...
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 t...
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 nod...
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 example...
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 i...
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 ext...
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 de...
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 sche...
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 ...
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(( ( ",*...
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 algorith...
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 ...
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...
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 ...
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 ap...
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 ...
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 abstr...
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 f...
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 ex...
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 n...
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 (cod...
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...
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 p...
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 ...
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 rootparentleftrighthaslefthasrightisinternalisexternalan...
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 ...
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 parenthes...
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...
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 expre...
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 alg...
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 o...
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 comp...
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 ...
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 constan...
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 cou...
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 o...
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 ...
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 oper...
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 sto...
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/ ...
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 fra...
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 posto...
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 c...
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 exter...
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...
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 inte...
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 ...
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 it...
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 ...
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 o...
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 bin...
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 bi...
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 c...
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 desce...
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 f...
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 pa...
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 ...
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 compari...
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 c...
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...
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...
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 u...
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 ...
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 sort...
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 th...
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...
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 u...