id
int64
0
25.6k
text
stringlengths
0
4.59k
22,900
binary trees when you're done evaluating the postfix stringyou pop the one remaining item off the stack somewhat amazinglythis item is complete tree depicting the algebraic expression you can see the prefix and infix representations of the original postfix (and recover the postfix expressionby traversing the tree as we...
22,901
last currentcurrent current leftchildreturn last/remember node /go to left child we'll need to know about finding the minimum value when we set about deleting node for the maximum value in the treefollow the same procedurebut go from right child to right child until you find node with no right child this node is the ma...
22,902
binary trees null abefore deletion figure awaiting garbage collection bafter deletion deleting node with no children using the workshop applet to delete node with no children assume you're going to delete node in figure press the del button and enter when prompted againthe node must be found before it can be deleted re...
22,903
isleftchild falsecurrent current rightchildif(current =null/end of the linereturn false/didn' find it /end while /found node to delete /continues after we've found the nodewe check first to verify that it has no children when this is truewe check the special case of the root if that' the node to be deletedwe simply set...
22,904
binary trees to be deleted abefore deletion figure bafter deletion deleting node with one child pressing del once more causes to be deleted its place is taken by its left child in factthe entire subtree of which is the root is moved up and plugged in as the new right child of use the workshop applet to generate new tre...
22,905
root current leftchildelse if(isleftchild/left child of parent parent leftchild current leftchildelse /right child of parent parent rightchild current leftchild/if no left childreplace with right subtree else if(current leftchild==nullif(current =rootroot current rightchildelse if(isleftchild/left child of parent paren...
22,906
binary trees to be deleted which node goes here successor root of right subtree bafter deletion abefore deletion figure cannot replace with subtree to be deleted successor to abefore deletion figure bafter deletion node replaced by its successor finding the successor how do you find the successor of nodeas human beingy...
22,907
long to see that the successor of is there' just no other number that is greater than and also smaller than howeverthe computer can' do things "at glance"it needs an algorithm here it isfirstthe program goes to the original node' right childwhich must have key larger than the node then it goes to this right child' left...
22,908
binary trees to find successor of this node go to right child successor no left child figure the right child is the successor using the workshop applet to delete node with two children generate tree with the workshop appletand pick node with two children now mentally figure out which node is its successorby going to it...
22,909
node successor delnodenode current delnode rightchildwhile(current !nullsuccessorparent successorsuccessor currentcurrent current leftchild/go to right child /until no more /left children/go to left child /if successor not if(successor !delnode rightchild/right child/make connections successorparent leftchild successor...
22,910
binary trees here are the code statements that carry out these stepsexcerpted from delete() parent rightchild successor successor leftchild current leftchildthis situation is summarized in figure which shows the connections affected by these two steps successor' parent to be deleted ("current"parent step step step step...
22,911
return true/end delete(notice that this is--finally--the end of the delete(routine let' review the code for these two stepsstep if the node to be deletedcurrentis the rootit has no parent so we merely set the root to the successor otherwisethe node to be deleted can be either left or right child (figure shows it as rig...
22,912
binary trees unplug current from the rightchild field of its parentand set this field to point to successor unplug current' left child from currentand plug it into the leftchild field of successor steps and are handled in the getsuccessor(routinewhile and are carried out in delete(figure shows the connections affected ...
22,913
/if successor not if(successor !delnode rightchild/right child/make connections successorparent leftchild successor rightchildsuccessor rightchild delnode rightchildthese steps are more convenient to perform here than in delete()because in getsuccessor(we can easily figure out where the successor' parent is while we're...
22,914
binary trees table number of levels for specified number of nodes number of nodes number of levels , , , , , , , , , this situation is very much like the ordered array discussed in in that casethe number of comparisons for binary search was approximately equal to the base logarithm of the number of cells in the array h...
22,915
in an ordered array you can find an item equally quicklybut inserting an item requireson the averagemoving , items inserting an item in tree with , , items requires or fewer comparisonsplus small amount of time to connect the item similarlydeleting an item from , , -item array requires moving an average of , itemswhile...
22,916
binary trees (where the character indicates integer division with no remainderyou can check this out by looking at figure array null null null null null figure tree represented by an array in most situationsrepresenting tree with an array isn' very efficient unfilled nodes and deleted nodes leave holes in the arraywast...
22,917
one option is to simply forbid duplicate keys when duplicate keys are excluded by the nature of the data (employee id numbersfor example)there' no problem otherwiseyou need to modify the insert(routine to check for equality during the insertion processand abort the insertion if duplicate is found the fill routine in th...
22,918
binary trees the display shows the key values arranged in something of tree shapehoweveryou'll need to imagine the edges two dashes (--represent node that doesn' exist at particular position in the tree the program initially creates some nodes so the user will have something to see before any insertions are made you ca...
22,919
listing continued /public node find(int key/find node with given key /(assumes non-empty treenode current root/start at root while(current idata !key/while no matchif(key current idata/go leftcurrent current leftchildelse /or go rightcurrent current rightchildif(current =null/if no childreturn null/didn' find it return...
22,920
binary trees listing continued current current rightchildif(current =null/if end of the line /insert on right parent rightchild newnodereturn/end else go right /end while /end else not root /end insert(/public boolean delete(int key/delete node with given key /(assumes non-empty listnode current rootnode parent rootboo...
22,921
listing continued else if(isleftchildparent leftchild nullelse parent rightchild null/disconnect /from parent /if no right childreplace with left subtree else if(current rightchild==nullif(current =rootroot current leftchildelse if(isleftchildparent leftchild current leftchildelse parent rightchild current leftchild/if...
22,922
binary trees listing continued return true/success /end delete(//returns node with next-highest value after delnode /goes to right childthen right child' left descendents private node getsuccessor(node delnodenode successorparent delnodenode successor delnodenode current delnode rightchild/go to right child while(curre...
22,923
listing continued /private void preorder(node localrootif(localroot !nullsystem out print(localroot idata ")preorder(localroot leftchild)preorder(localroot rightchild)/private void inorder(node localrootif(localroot !nullinorder(localroot leftchild)system out print(localroot idata ")inorder(localroot rightchild)/privat...
22,924
binary trees listing continued stack localstack new stack()isrowempty truefor(int = <nblanksj++system out print(')while(globalstack isempty()==falsenode temp (node)globalstack pop()if(temp !nullsystem out print(temp idata)localstack push(temp leftchild)localstack push(temp rightchild)if(temp leftchild !null |temp right...
22,925
listing continued public static void main(string[argsthrows ioexception int valuetree thetree new tree()thetree insert( )thetree insert( )thetree insert( )thetree insert( )thetree insert( )thetree insert( )thetree insert( )thetree insert( )thetree insert( )thetree insert( )thetree insert( )while(truesystem out print("e...
22,926
binary trees listing continued else system out print("could not find ")system out print(value '\ ')breakcase ' 'system out print("enter value to delete")value getint()boolean diddelete thetree delete(value)if(diddeletesystem out print("deleted value '\ ')else system out print("could not delete ")system out print(value ...
22,927
listing continued string getstring()return integer parseint( )//end class treeapp ///////////////////////////////////////////////////////////////you can use the + key combination to exit from this programin the interest of simplicity there' no single-letter key for this action the huffman code you shouldn' get the idea...
22,928
binary trees there are several approaches to compressing data for textthe most common approach is to reduce the number of bits that represent the most-used characters in englishe is often the most common letterso it seems reasonable to use as few bits as possible to encode it on the other handz is seldom usedso using l...
22,929
table continued character code space linefeed we use for and for the space we can' use or because they are prefixes for other characters what about -bit combinationsthere are eight possibilities and is and is why aren' any other combinations usedwe already know we can' use anything starting with or that eliminates four...
22,930
binary trees sp lf figure huffman tree you'll see you can do the same with the other characters if you have the patienceyou can decode the entire bit string this way creating the huffman tree we've seen how to use the huffman tree for decodingbut how do we create this treethere are many ways to handle this problem we'l...
22,931
now do the following remove two trees from the priority queueand make them into children of new node the new node has frequency that is the sum of the children' frequenciesits character field can be left blank insert this new three-node tree back into the priority queue keep repeating steps and the trees will get large...
22,932
binary trees sp lf sp lf sp lf figure sp growing the huffman treepart coding the message now that we have the huffman treehow do we code messagewe start by creating code tablewhich lists the huffman code alongside each character to simplify the discussionlet' assume thatinstead of the ascii codeour computer uses simpli...
22,933
codeonly those that appear in the message figure shows how this looks for the susie message figure space linefeed code table such code table makes it easy to generate the coded messagefor each character in the original messagewe use its code as an index into the code table we then repeatedly append the huffman codes to...
22,934
binary trees summary trees consist of nodes (circlesconnected by edges (linesthe root is the topmost node in treeit has no parent in binary treea node has at most two children in binary search treeall the nodes that are left descendants of node have key values less than aall the nodes that are ' right descendants have ...
22,935
nodes with duplicate key values may cause trouble in arrays because only the first one can be found in search trees can be represented in the computer' memory as an arrayalthough the reference-based approach is more common huffman tree is binary tree (but not search treeused in data-compression algorithm called huffman...
22,936
binary trees finding node in binary search tree involves going from node to nodeasking how big the node' key is in relation to the search key how big the node' key is compared to its right or left children what leaf node we want to reach what level we are on an unbalanced tree is one in which most of the keys have valu...
22,937
in coding character you typically start at leaf and work upward the tree can be generated by removal and insertion operations on priority queue experiments carrying out these experiments will help to provide insights into the topics covered in the no programming is involved use the binary tree workshop applet to create...
22,938
binary trees one way to begin is by making an array of trees ( group of unconnected trees is called forest take each letter typed by the user and put it in node take each of these nodes and put it in treewhere it will be the root now put all these one-node trees in the array start by making new tree with at the root an...
22,939
write program that transforms postfix expression into tree such as that shown in figure in this you'll need to modify the tree class from the tree java program (listing and the parsepost class from the postfix java program (listing in there are more details in the discussion of figure after the tree is generatedtravers...
22,940
red-black trees in this our approach to the discussion balanced and unbalanced you learned in "binary trees,ordinary binary search trees offer important advantages as data storage devicesyou can quickly search for an item with given keyand you can also quickly insert or delete an item other data storage structuressuch ...
22,941
red-black trees symmetrical cases (for left or right childreninside or outside grandchildrenand so on)the actual code is more lengthy and complex than one might expect it' therefore hard to learn about the algorithm by examining code accordinglythere are no listings in this you can create similar functionality using tr...
22,942
figure items inserted in ascending order degenerates to (nwhen there are no branchesthe tree becomesin effecta linked list the arrangement of data is one-dimensional instead of two-dimensional unfortunatelyas with linked listyou must now search through (on the averagehalf the items to find the one you're looking for in...
22,943
red-black trees figure partially unbalanced tree with realistic amount of random datait' not likely tree would become seriously unbalanced howeverthere may be runs of sorted data that will partially unbalance tree searching partially unbalanced trees will take time somewhere between (nand (logn)depending on how badly t...
22,944
colored nodes in red-black treeevery node is either black or red these are arbitrary colorsblue and yellow would do just as well in factthe whole concept of saying that nodes have "colorsis somewhat arbitrary some other analogy could have been used insteadwe could say that every node is either heavy or lightor yin or y...
22,945
red-black trees you can see how the rules work by using the rbtree workshop applet we'll do some experiments with the applet in momentbut first you should understand what actions you can take to fix things if one of the red-black rules is broken duplicate keys what happens if there' more than one data item with the sam...
22,946
figure the rbtree workshop applet clicking on node the red arrow points to the currently selected node it' this node whose color is changed or which is the top node in rotation you select node by single-clicking it with the mousewhich moves the red arrow to the node the start button when you first start the rbtree work...
22,947
red-black trees to insert the nodewhich is similar to that in ordinary binary search treesbut on keeping the tree balancedso the applet doesn' show the individual steps in the insertion the del button pushing the del button causes the node with the key value typed into the number box to be deleted as with the ins butto...
22,948
text messages messages in the text box below the buttons tell you whether the tree is red-black correct the tree is red-black correct if it adheres to rules through listed previously if it' not correctyou'll see messages advising which rule is being violated in some cases the red arrow will point to the place where the...
22,949
red-black trees black node figure red node red node balanced tree alsoit' easier to fix violations of rule (parent and child are both redthan rule (black heights differ)as we'll see later experiment rotations let' try some rotations start with the three nodes as shown in figure position the red arrow on the root ( by c...
22,950
experiment color flips start with the position of figure with nodes and inserted in addition to in the root position note that the parent (the rootis black and both its children are red now try to insert another node no matter what value you useyou'll see the message can' insertneeds color flip as we mentioneda color f...
22,951
red-black trees figure red parent and child violates rule changing this to black violates rule parent and child are both red how can we fix the tree so rule isn' violatedan obvious approach is to change one of the offending nodes to black let' try changing the child node position the red arrow on it and press the / but...
22,952
have more black nodesviolating rule or it must have two adjacent red nodesviolating rule convince yourself that this is true by experimenting with the applet null children remember that rule specifies all paths that go from the root to any leaf or to any null children must have the same number of black nodes null child...
22,953
red-black trees raise some nodes and lower others to help balance the tree ensure that the characteristics of binary search tree are not violated recall that in binary search tree the left children of any node have key values less than the nodewhile its right children have key values greater than or equal to the node i...
22,954
when you try to insert the you'll see the can' insertneeds color flip message just click the flip button the parent and children change color then press ins again to complete the insertion of the finallyinsert the the resulting arrangement is shown in figure crossover node crossover node figure rotation with crossover ...
22,955
red-black trees subtrees on the move we've shown individual nodes changing position during rotationbut entire subtrees can move as well to see thisclick start to put at the rootand then insert the following sequence of nodes in order click flip whenever you can' complete an insertion because of the can' insertneeds col...
22,956
position the arrow on the root now press ror wow(or is it wow? lot of nodes have changed position the result is shown in figure here' what happensthe top node ( goes to its right child the top node' left child ( goes to the top the entire subtree of which is the root moves up the entire subtree of which is the root mov...
22,957
red-black trees preview of the insertion process we're going to briefly preview our approach to describing the insertion process don' worry if things aren' completely clear in the previewwe'll discuss this process in more detail in moment in the discussion that followswe'll use xpand to designate pattern of related nod...
22,958
where the node should be insertedgoing left or right at each node depending on the relative size of the node' key and the search key howeverin red-black treegetting to the insertion point is complicated by color flips and rotations we introduced color flips in experiment now we'll look at them in more detail imagine th...
22,959
red-black trees violation of rule although rule is not violated by color fliprule ( node and its parent can' both be redmay be if the parent of is blackthere' no problem when is changed from black to red howeverif the parent of is redthenafter the color changewe'll have two reds in row this problem needs to be fixed be...
22,960
abg outside grandchild (left childcinside grandchild (right childdg inside grandchild (left childfigure outside grandchild (right childhanded variations of node being inserted the action we take to restore the red-black rules is determined by the colors and configuration of and its relatives perhaps surprisinglynodes c...
22,961
red-black trees black either grandchild apossibility is black red grandchild outside bpossibility is redand is outside red inside grandchild cpossibility is redand is inside figure three post-insertion possibilities possibility is black if is blackwe get free ride the node we've just inserted is always red if its paren...
22,962
acolor change rotation color change figure is red and is an outside grandchild in this situationwe can take three steps to restore red-black correctness and thereby balance the tree here are the steps switch the color of ' grandparent ( in this example switch the color of ' parent ( rotate with ' grandparent ( at the t...
22,963
red-black trees (againyou'll need color flip before you insert the the result is shown in figure note that the node is an inside grandchild it and its parent are both redso again you see the error message errorparent and child both red fixing this arrangement is slightly more complicated if we try to rotate right with ...
22,964
we must also recolor the nodes we do this before doing any rotations (this order doesn' really matterbut if we wait until after the rotations to recolor the nodesit' hard to know what to call them here are the steps switch the color of ' grandparent ( in this example switch the color of (not its parentx is here rotate ...
22,965
red-black trees the entire tree actuallyproving this is beyond the scope of this bookbut such proof is possible the color flips on the way down make insertion in red-black trees more efficient than in other kinds of balanced treessuch as avl trees they ensure that you need to pass through the tree only onceon the way d...
22,966
switch the color of ' grandparent ( in this exampleignore the message that the root must be black switch the color of ' parent ( rotate with ' grandparent ( at the topin the direction that raises (here right rotationg change color rotate change color figure color flip changes and new node inserted outside grandchild on...
22,967
red-black trees click start in the rbtree workshop applet to begin with and insert and you'll need color flips before and now try to insert new node with the value you'll be told you need color flip (at but when you perform the flip and are both redand you get the errorparent and child are both red message don' press i...
22,968
to cure the red-red conflictyou must do the same two color changes and two rotations as in possibility change the color of (it' ignore the message that the root must be black change the color of ( rotate with ( as the topin the direction that raises (left in this examplethe result is shown in figure rotate with ( as th...
22,969
red-black trees the times for insertion and deletion are increased by constant factor because of having to perform color flips and rotations on the way down and at the insertion point on the averagean insertion requires about one rotation thereforeinsertion still takes (log ntime but is slower than insertion in the ord...
22,970
not be larger than that isthe height of node' left subtree may be no more than one level different from the height of its right subtree following insertionthe root of the lowest subtree into which the new node was inserted is checked if the height of its children differs by more than single or double rotation is perfor...
22,971
red-black trees after new node is insertedred-red conflicts are checked again if violation is foundappropriate rotations are carried out to make the tree red-black correct these adjustments result in the tree being balancedor at least almost balanced adding red-black balancing to binary tree has only small negative eff...
22,972
the two possible actions used to balance tree are and newly inserted nodes are always colored which of the following is not involved in rotationa rearranging nodes to restore the characteristics of binary search tree changing the color of nodes ensuring the red-black rules are followed attempting to balance the tree "c...
22,973
red-black trees experiments carrying out these experiments will help to provide insights into the topics covered in the no programming is involved make an activity diagram or flowchart of all the node arrangements and colors you can encounter when inserting new node in red-black treeand what you should do in each situa...
22,974
trees and external storage in this introduction to trees java code for tree trees and red-black trees in binary treeeach node has one data item and can have up to two children if we allow more data items and children per nodethe result is multiway tree treesto which we devote the first part of this are multiway trees t...
22,975
trees and external storage figure tree here the top three nodes have childrenand the six nodes on the bottom row are all leaf nodeswhich by definition have no children in tree all the leaf nodes are always on the same level what' in namethe and in the name tree refer to how many links to child nodes can potentially be ...
22,976
in treeon the other handnodes with single link are not permitted node with one data item must always have two linksunless it' leafin which case it has no links figure shows the possibilities node with two links is called -nodea node with three links is -nodeand node with four links is -nodebut there is no such thing as...
22,977
trees and external storage all children in the subtree rooted at child have key values greater than key but less than key all children in the subtree rooted at child have key values greater than key this relationship is shown in figure duplicate values are not usually permitted in treesso we don' need to worry about co...
22,978
insertion into tree is sometimes quite easy and sometimes rather complicated in any case the process begins by searching for the appropriate leaf node if no full nodes are encountered during the searchinsertion is easy when the appropriate leaf node is reachedthe new data item is simply inserted into it figure shows da...
22,979
trees and external storage data item is moved into the parent of the node being split data item remains where it is the rightmost two children are disconnected from the node being split and connected to the new node an example of node split is shown in figure another way of describing node split is to say that -node ha...
22,980
data item is moved into the new sibling data item is moved into the new root data item remains where it is the two rightmost children of the node being split are disconnected from it and connected to the new right-hand node figure shows the root being split this process creates new root that' at higher level than the o...
22,981
trees and external storage is guaranteed not to be full and can therefore accept data item without itself needing to be split of courseif this parent already had two children when its child was splitit will become full howeverthat just means that it will be split when the next search encounters it figure shows series o...
22,982
figure the tree workshop applet the fill button when it' first startedthe tree workshop applet inserts data items into the tree you can use the fill button to create new tree with different number of data items from to click fill and type the number into the field when prompted another click will create the new tree th...
22,983
trees and external storage in the tree workshop applet it' important to complete each operation before attempting new one continue to click the button until the message says press any button this is the signal that an operation is complete the ins button the ins button causes new data itemwith key specified in the text...
22,984
in this view nodes are shown as small rectanglesdata items are not shown nodes that exist and are visible in the zoomed-in view (which you can restore by clicking zoom againare shown in green nodes that exist but aren' currently visible in the zoomed-out view are shown in magentaand nodes that don' exist are shown in g...
22,985
trees and external storage figure selecting the leftmost children figure selecting the rightmost children experiments the tree workshop applet offers quick way to learn about trees try inserting items into the tree watch for node splits stop before one is about to happenand figure out where the three data items from th...
22,986
how many data items can you insert in the treethere' limit because only four levels are allowed four levels can potentially contain nodesfor total of nodes (all visible on the zoomed-out displayif there were full items per nodethere would be data items howeverthe nodes can' all be full at the same time long before they...
22,987
trees and external storage we've chosen to store the number of items currently in the node (numitemsand the node' parent (parentas fields in this class neither of these fields is strictly necessary and could be eliminated to make the nodes smaller howeverincluding them clarifies the programmingand only small price is p...
22,988
from the node and stored then the two rightmost children are disconnectedtheir references are also stored new nodecalled newrightis created it will be placed to the right of the node being split if the node being split is the rootan additional new node is createda new root nextappropriate connections are made to the pa...
22,989
trees and external storage level= child= / / level= child= / / level= child= / level= child= / / the output is not very intuitivebut there' enough information to draw the tree if you want the levelstarting with at the rootis shownas well as the child number the display algorithm is depth-firstso the root is shown first...
22,990
listing continued public long ddata/one data item //public dataitem(long dd/constructor ddata dd//public void displayitem(/display itemformat "/ system out print("/"+ddata)///end class dataitem ///////////////////////////////////////////////////////////////class node private static final int order private int numitemsp...
22,991
listing trees and external storage continued return (childarray[ ]==nulltrue false/public int getnumitems(return numitems/public dataitem getitem(int index/get dataitem at index return itemarray[index]/public boolean isfull(return (numitems==order- true false/public int finditem(long key/return index of /item (within n...
22,992
listing continued return + /return index to /new item /end else (not null/end for /shifted all itemsitemarray[ newitem/insert new item return /end insertitem(/public dataitem removeitem(/remove largest item /assumes node not empty dataitem temp itemarray[numitems- ]/save item itemarray[numitems- null/disconnect it numi...
22,993
trees and external storage listing continued curnode getnextchild(curnodekey)/end while //insert dataitem public void insert(long dvaluenode curnode rootdataitem tempitem new dataitem(dvalue)while(trueifcurnode isfull(split(curnode)curnode curnode getparent()/if node full/split it /back up /search once curnode getnextc...
22,994
listing continued node newright new node()/make new node if(thisnode==root/if this is the rootroot new node()/make new root parent root/root is our parent root connectchild( thisnode)/connect to parent else /this node not the root parent thisnode getparent()/get parent /deal with parent itemindex parent insertitem(item...
22,995
listing trees and external storage continued return thenode getchild( )/return right child /public void displaytree(recdisplaytree(root )/private void recdisplaytree(node thisnodeint levelint childnumbersystem out print("level="+level+child="+childnumber+")thisnode displaynode()/display this node /call ourselves for ea...
22,996
listing continued while(truesystem out print("enter first letter of ")system out print("showinsertor find")char choice getchar()switch(choicecase ' 'thetree displaytree()breakcase ' 'system out print("enter value to insert")value getint()thetree insert(value)breakcase ' 'system out print("enter value to find")value get...
22,997
listing trees and external storage continued return charat( )//public static int getint(throws ioexception string getstring()return integer parseint( )///end class tree app ///////////////////////////////////////////////////////////////trees and red-black trees at this point trees and red-black trees (described in prob...
22,998
transform any -node into parent and two childrenas shown in figure the first child has its own children and xthe second child has children and as beforethe children are colored red and the parent is black -node black -node black either of these is valid -node black figure red transformationsto red-black figure shows tr...
22,999
trees and external storage atree bred-black tree black node red node figure tree and its red-black equivalent operational equivalence not only does the structure of red-black tree correspond to treebut the operations applied to these two kinds of trees are also equivalent in tree the tree is kept balanced using node sp...