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 described we'll leave an implementation of this process as an exercise finding maximum and minimum values incidentallywe should note how easy it is to find the maximum and minimum values in binary search tree in factthis process is so easy we don' include it as an option in the workshop appletnor show code for it in listing stillunderstanding how it works is important for the minimumgo to the left child of the rootthen go to the left child of that childand so onuntil you come to node that has no left child this node is the minimumas shown in figure minimum figure minimum value of tree here' some code that returns the node with the minimum key valuepublic node minimum(/returns node with minimum key value node currentlastcurrent root/start at root while(current !null/until the bottom
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 maximum the code is the same except that the last statement in the loop is current current rightchild/go to right child deleting node deleting node is the most complicated common operation required for binary search trees howeverdeletion is important in many tree applicationsand studying the details builds character you start by finding the node you want to deleteusing the same approach we saw in find(and insert(when you've found the nodethere are three cases to consider the node to be deleted is leaf (has no children the node to be deleted has one child the node to be deleted has two children we'll look at these three cases in turn the first is easythe secondalmost as easyand the thirdquite complicated case the node to be deleted has no children to delete leaf nodeyou simply change the appropriate child field in the node' parent to point to nullinstead of to the node the node will still existbut it will no longer be part of the tree this is shown in figure because of java' garbage collection featurewe don' need to worry about explicitly deleting the node itself when java realizes that nothing in the program refers to the nodeit will be removed from memory (in and +you would need to execute free(or delete(to remove the node from memory
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 repeatedly pressing del will take you from to to when the node is foundit' deleted without incident java code to delete node with no children the first part of the delete(routine is similar to find(and insert(it involves finding the node to be deleted as with insert()we need to remember the parent of the node to be deleted so we can modify its child fields if we find the nodewe drop out of the while loop with parent containing the node to be deleted if we can' find itwe return from delete(with value of false public boolean delete(int key/delete node with given key /(assumes non-empty listnode current rootnode parent rootboolean isleftchild truewhile(current idata !key/search for node parent currentif(key current idata/go leftisleftchild truecurrent current leftchildelse /or go right
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 it to nullthis empties the tree otherwisewe set the parent' leftchild or rightchild field to null to disconnect the parent from the node /delete(continued /if no childrensimply delete it if(current leftchild==null &current rightchild==nullif(current =root/if rootroot null/tree is empty else if(isleftchildparent leftchild null/disconnect else /from parent parent rightchild null/continues case the node to be deleted has one child this second case isn' so bad either the node has only two connectionsto its parent and to its only child you want to "snipthe node out of this sequence by connecting its parent directly to its child this process involves changing the appropriate reference in the parent (leftchild or rightchildto point to the deleted node' child this situation is shown in figure using the workshop applet to delete node with one child let' assume we're using the workshop applet on the tree in figure and deleting node which has left child but no right child press del and enter when prompted keep pressing del until the arrow rests on node has only one child it doesn' matter whether has children of its ownin this case it has one
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 trees with one-child nodesand see what happens when you delete them look for the subtree whose root is the deleted node' child no matter how complicated this subtree isit' simply moved up and plugged in as the new child of the deleted node' parent java code to delete node with one child the following code shows how to deal with the one-child situation there are four variationsthe child of the node to be deleted may be either left or right childand for each of these cases the node to be deleted may be either the left or right child of its parent there is also specialized situationthe node to be deleted may be the rootin which case it has no parent and is simply replaced by the appropriate subtree here' the code (which continues from the end of the no-child code fragment shown earlier)/delete(continued /if no right childreplace with left subtree else if(current rightchild==nullif(current =root
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 parent leftchild current rightchildelse /right child of parent parent rightchild current rightchild/continued notice that working with references makes it easy to move an entire subtree you do this by simply disconnecting the old reference to the subtree and creating new reference to it somewhere else although there may be lots of nodes in the subtreeyou don' need to worry about moving them individually in factthey "moveonly in the sense of being conceptually in different positions relative to the other nodes as far as the program is concernedonly the reference to the root of the subtree has changed case the node to be deleted has two children now the fun begins if the deleted node has two childrenyou can' just replace it with one of these childrenat least if the child has its own children why notexamine figure and imagine deleting node and replacing it with its right subtreewhose root is which left child would havethe deleted node' left child or the new node' left child in either case would be in the wrong placebut we can' just throw it away we need another approach the good news is that there' trick the bad news is thateven with the trickthere are lot of special cases to consider remember that in binary search tree the nodes are arranged in order of ascending keys for each nodethe node with the next-highest key is called its inorder successoror simply its successor in figure anode is the successor of node here' the trickto delete node with two childrenreplace the node with its inorder successor figure shows deleted node being replaced by its successor notice that the nodes are still in order (there' more to it if the successor itself has childrenwe'll look at that possibility in moment
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 beingyou can do this quickly (for small treesanywayjust take quick glance at the tree and find the next-largest number following the key of the node to be deleted in figure it doesn' take
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 child (if it has one)and to this left child' left childand so onfollowing down the path of left children the last left child in this path is the successor of the original nodeas shown in figure to find successor of this node go to right child go to left child go to left child successor no left child figure finding the successor why does this algorithm workwhat we're really looking for is the smallest of the set of nodes that are larger than the original node when you go to the original node' right childall the nodes in the resulting subtree are greater than the original node because this is how binary search tree is defined now we want the smallest value in this subtree as we learnedyou can find the minimum value in subtree by following the path down all the left children thusthis algorithm finds the minimum value that is greater than the original nodethis is what we mean by its successor if the right child of the original node has no left childrenthis right child is itself the successoras shown in figure
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 its right child and then following down the line of this right child' left children (if it has anyyou may want to make sure the successor has no children of its own if it doesthe situation gets more complicated because entire subtrees are moved aroundrather than single node after you've chosen node to deleteclick the del button you'll be asked for the key value of the node to delete when you've specified itrepeated presses of the del button will show the red arrow searching down the tree to the designated node when the node is deletedit' replaced by its successor let' assume you use the workshop applet to delete the node with key from the example shown earlier in figure the red arrow will go from the root at to then will be replaced by java code to find the successor here' some code for method getsuccessor()which returns the successor of the node specified as its delnode argument (this routine assumes that delnode does indeed have right childbut we know this is true because we've already determined that the node to be deleted has two children /returns node with next-highest value after delnode /goes to right childthen right child' left descendants private node getsuccessor(node delnodenode successorparent delnode
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 rightchildsuccessor rightchild delnode rightchildreturn successorthe routine first goes to delnode' right child and thenin the while loopfollows down the path of all this right child' left children when the while loop exitssuccessor contains delnode' successor when we've found the successorwe may need to access its parentso within the while loop we also keep track of the parent of the current node the getsuccessor(routine carries out two additional operations in addition to finding the successor howeverto understand themwe need to step back and consider the big picture as we've seenthe successor node can occupy one of two possible positions relative to currentthe node to be deleted the successor can be current' right childor it can be one of this right child' left descendants we'll look at these two situations in turn successor is right child of delnode if successor is the right child of currentthings are simplified somewhat because we can simply move the subtree of which successor is the root and plug it in where the deleted node was this operation requires only two steps unplug current from the rightchild field of its parent (or leftchild field if appropriate)and set this field to point to successor unplug current' left child from currentand plug it into the leftchild field of 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 successor cannot exist abefore deletion figure bafter deletion deletion when the successor is the right child here' the code in context ( continuation of the else-if ladder shown earlier)/delete(continued else /two childrenso replace with inorder successor /get successor of node to delete (currentnode successor getsuccessor(current)/connect parent of current to successor instead if(current =rootroot successorelse if(isleftchildparent leftchild successorelse parent rightchild successor/connect successor to current' left child successor leftchild current leftchild/end else two children /(successor cannot have left child
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 right child)so we set the appropriate field in its parent to point to successor when delete(returns and current goes out of scopethe node referred to by current will have no references to itso it will be discarded during java' next garbage collection step we set the left child of successor to point to current' left child what happens if the successor has children of its ownfirst of alla successor node is guaranteed not to have left child this is true whether the successor is the right child of the node to be deleted or one of this right child' left children how do we know thiswellremember that the algorithm we use to determine the successor goes to the right child first and then to any left children of that right child it stops when it gets to node with no left childso the algorithm itself determines that the successor can' have any left children if it didthat left child would be the successor instead you can check this out on the workshop applet no matter how many trees you makeyou'll never find situation in which node' successor has left child (assuming the original node has two childrenwhich is the situation that leads to all this trouble in the first placeon the other handthe successor may very well have right child this isn' much of problem when the successor is the right child of the node to be deleted when we move the successorits right subtree simply follows along with it there' no conflict with the right child of the node being deleted because the successor is this right child in the next section we'll see that successor' right child needs more attention if the successor is not the right child of the node to be deleted successor is left descendant of right child of delnode if successor is left descendant of the right child of the node to be deletedfour steps are required to perform the deletion plug the right child of successor into the leftchild field of the successor' parent plug the right child of the node to be deleted into the rightchild field of successor
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 by these four steps parent step step to be deleted step successor' step parent step step step successor step step cannot exist successor' right child abefore deletion figure bafter deletion deletion when the successor is the left child here' the code for these four steps successorparent leftchild successor rightchild successor rightchild delnode rightchild parent rightchild successor successor leftchild current leftchild(step could also refer to the left child of its parent the numbers in figure show the connections affected by the four steps step in effect replaces the successor with its right subtree step keeps the right child of the deleted node in its proper place (this happens automatically when the successor is the right child of the deleted nodesteps and are carried out in the if statement that ends the getsuccessor(method shown earlier here' that statement again
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 descending the tree to find the successor steps and we've seen alreadythey're the same as steps and in the case where the successor is the right child of the node to be deletedand the code is in the if statement at the end of delete(is deletion necessaryif you've come this faryou can see that deletion is fairly involved in factit' so complicated that some programmers try to sidestep it altogether they add new boolean field to the node classcalled something like isdeleted to delete nodethey simply set this field to true then other operationslike find()check this field to be sure the node isn' marked as deleted before working with it this waydeleting node doesn' change the structure of the tree of courseit also means that memory can fill up with "deletednodes this approach is bit of cop-outbut it may be appropriate where there won' be many deletions in tree (if ex-employees remain in the personnel file foreverfor example the efficiency of binary trees as you've seenmost operations with trees involve descending the tree from level to level to find particular node how long does it take to do thisin full treeabout half the nodes are on the bottom level (more accuratelyif it' fullthere' one more node on the bottom row than in the rest of the tree thusabout half of all searches or insertions or deletions require finding node on the lowest level (an additional quarter of these operations require finding the node on the next-to-lowest leveland so on during search we need to visit one node on each level so we can get good idea how long it takes to carry out these operations by knowing how many levels there are assuming full treetable shows how many levels are necessary to hold given number of nodes
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 hereif we call the number of nodes in the first column nand the number of levels in the second column lwe can say that is less than raised to the power lor adding to both sides of the equationwe have this is equivalent to log ( thusthe time needed to carry out the common tree operations is proportional to the base log of in big notation we say such operations take (logntime if the tree isn' fullanalysis is difficult we can say that for tree with given number of levelsaverage search times will be shorter for the non-full tree than the full tree because fewer searches will proceed to lower levels compare the tree to the other data storage structures we've discussed so far in an unordered array or linked list containing , , itemsfinding the item you want takeson the average , comparisons but in tree of , , itemsonly (or fewercomparisons are required
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 deleting an item from , , -node tree requires or fewer comparisons to find the itemplus (possiblya few more comparisons to find its successorplus short time to disconnect the item and connect its successor thusa tree provides high efficiency for all the common data storage operations traversing is not as fast as the other operations howevertraversals are probably not very commonly carried out in typical large database they're more appropriate when tree is used as an aid to parsing algebraic or similar expressionswhich are probably not too long anyway trees represented as arrays our code examples are based on the idea that tree' edges are represented by leftchild and rightchild references in each node howeverthere' completely different way to represent treewith an array in the array approachthe nodes are stored in an array and are not linked by references the position of the node in the array corresponds to its position in the tree the node at index is the rootthe node at index is the root' left childand so onprogressing from left to right along each level of the tree this is shown in figure every position in the treewhether it represents an existing node or notcorresponds to cell in the array adding node at given position in the tree means inserting the node into the equivalent cell in the array cells representing tree positions with no nodes are filled with or null with this schemea node' children and parent can be found by applying some simple arithmetic to the node' index number in the array if node' index number is indexthis node' left child is *index its right child is *index and its parent is (index-
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 arraywasting memory even worsewhen deletion of node involves moving subtreesevery node in the subtree must be moved to its new location in the arraywhich is time-consuming in large trees howeverif deletions aren' allowedthe array representation may be usefulespecially if obtaining memory for each node dynamically isfor some reasontoo timeconsuming the array representation may also be useful in special situations the tree in the workshop appletfor exampleis represented internally as an array to make it easy to map the nodes from the array to fixed locations on the screen display duplicate keys as in other data structuresthe problem of duplicate keys must be addressed in the code shown for insert()and in the workshop appleta node with duplicate key will be inserted as the right child of its twin the problem is that the find(routine will find only the first of two (or moreduplicate nodes the find(routine could be modified to check an additional data itemto distinguish data items even when the keys were the samebut this would be (at least somewhattime-consuming
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 the workshop applet excludes duplicates when generating the random keys the complete tree java program in this section we'll show the complete program that includes all the methods and code fragments we've looked at so far in this it also features primitive user interface this allows the user to choose an operation (findinginsertingdeletingtraversingand displaying the treeby entering characters the display routine uses character output to generate picture of the tree figure shows the display generated by the program figure output of the tree java program in the figurethe user has typed to display the treethen typed and to insert node with that valueand then again to display the tree with the additional node the appears in the lower display the available commands are the characters sifdand tfor showinsertfinddeleteand traverse the ifand options ask for the key value of the node to be operated on the option gives you choice of traversals for preorder for inorderand for postorder the key values are then displayed in that order
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 can modify this initialization code to start with any nodes you wantor with no nodes (which is good nodesyou can experiment with the program in listing as you can with the workshop applet unlike the workshop applethoweverit doesn' show you the steps involved in carrying out an operationit does everything at once listing the tree java program /tree java /demonstrates binary tree /to run this programc>java treeapp import java io *import java util */for stack class ///////////////////////////////////////////////////////////////class node public int idata/data item (keypublic double ddata/data item public node leftchild/this node' left child public node rightchild/this node' right child public void displaynode(/display ourself system out print('{')system out print(idata)system out print("")system out print(ddata)system out print("")/end class node ///////////////////////////////////////////////////////////////class tree private node root/first node of tree /public tree(/constructor root null/no nodes in tree yet
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 current/found it /end find(/public void insert(int iddouble ddnode newnode new node()/make new node newnode idata id/insert data newnode ddata ddif(root==null/no node in root root newnodeelse /root occupied node current root/start at root node parentwhile(true/(exits internallyparent currentif(id current idata/go leftcurrent current leftchildif(current =null/if end of the line/insert on left parent leftchild newnodereturn/end if go left else /or go right
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 rootboolean isleftchild truewhile(current idata !key/search for node parent currentif(key current idata/go leftisleftchild truecurrent current leftchildelse /or go rightisleftchild falsecurrent current rightchildif(current =null/end of the linereturn false/didn' find it /end while /found node to delete /if no childrensimply delete it if(current leftchild==null &current rightchild==nullif(current =root/if rootroot null/tree is empty
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 no left childreplace with right subtree else if(current leftchild==nullif(current =rootroot current rightchildelse if(isleftchildparent leftchild current rightchildelse parent rightchild current rightchildelse /two childrenso replace with inorder successor /get successor of node to delete (currentnode successor getsuccessor(current)/connect parent of current to successor instead if(current =rootroot successorelse if(isleftchildparent leftchild successorelse parent rightchild successor/connect successor to current' left child successor leftchild current leftchild/end else two children /(successor cannot have left child
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(current !null/until no more /left childrensuccessorparent successorsuccessor currentcurrent current leftchild/go to left child /if successor not if(successor !delnode rightchild/right child/make connections successorparent leftchild successor rightchildsuccessor rightchild delnode rightchildreturn successor/public void traverse(int traversetypeswitch(traversetypecase system out print("\npreorder traversal")preorder(root)breakcase system out print("\ninorder traversal")inorder(root)breakcase system out print("\npostorder traversal")postorder(root)breaksystem out println()
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)/private void postorder(node localrootif(localroot !nullpostorder(localroot leftchild)postorder(localroot rightchild)system out print(localroot idata ")/public void displaytree(stack globalstack new stack()globalstack push(root)int nblanks boolean isrowempty falsesystem out println")while(isrowempty==false
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 rightchild !nullisrowempty falseelse system out print("--")localstack push(null)localstack push(null)for(int = <nblanks* - ++system out print(')/end while globalstack not empty system out println()nblanks / while(localstack isempty()==falseglobalstack pushlocalstack pop()/end while isrowempty is false system out println")/end displaytree(//end class tree ///////////////////////////////////////////////////////////////class treeapp
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("enter first letter of show")system out print("insertfinddeleteor traverse")int choice getchar()switch(choicecase ' 'thetree displaytree()breakcase ' 'system out print("enter value to insert")value getint()thetree insert(valuevalue )breakcase ' 'system out print("enter value to find")value getint()node found thetree find(value)if(found !nullsystem out print("found")found displaynode()system out print("\ ")
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 '\ ')breakcase ' 'system out print("enter type or ")value getint()thetree traverse(value)breakdefaultsystem out print("invalid entry\ ")/end switch /end while /end main(/public static string getstring(throws ioexception inputstreamreader isr new inputstreamreader(system in)bufferedreader br new bufferedreader(isr)string br readline()return /public static char getchar(throws ioexception string getstring()return charat( )//public static int getint(throws ioexception
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 that binary trees are always search trees many binary trees are used in other ways we saw an example in figure where binary tree represents an algebraic expression in this section we'll discuss an algorithm that uses binary tree in surprising way to compress data it' called the huffman codeafter david huffman who discovered it in data compression is important in many situations an example is sending data over the internetwhereespecially over dial-up connectiontransmission can take long time an implementation of this scheme is somewhat lengthyso we won' show complete program insteadwe'll focus on the concepts and leave the implementation as an exercise character codes each character in normal uncompressed text file is represented in the computer by one byte (for the venerable ascii codeor by two bytes (for the newer unicodewhich is designed to work for all languages in these schemesevery character requires the same number of bits table shows how some characters are represented in binary using the ascii code as you can seeevery character takes bits table some ascii codes character decimal binary
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 large number of bits is not so bad suppose we use just two bits for esay we can' encode every letter of the alphabet in two bits because there are only four -bit combinations and can we use these four combinations for the four most-used charactersunfortunately not we must be careful that no character is represented by the same bit combination that appears at the beginning of longer code used for some other character for exampleif is and is then anyone decoding wouldn' know if the initial represented an or the beginning of an this leads to ruleno code can be the prefix of any other code something else to consider is that in some messages might not be the most-used character if the text is java source filefor examplethe (semicoloncharacter might appear more often than here' the solution to that problemfor each messagewe make up new code tailored to that particular message suppose we want to send the message susie says it is easy the letter appears lotand so does the space character we might want to make up table showing how many times each letter appears this is called frequency tableas shown in table table frequency table character count space linefeed the characters with the highest counts should be coded with small number of bits table shows how we might encode the characters in the susie message table huffman code character code
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 possibilities also is used at the beginning of and the linefeedand is used at the beginning of and only two -bit codes remainwhich we use for and in similar way we can see why only three -bit codes are available thusthe entire message is coded as for sanity reasons we show this message broken into the codes for individual characters of coursein reality all the bits would run togetherthere is no space character in binary messageonly and decoding with the huffman tree we'll see later how to create huffman codes firstwe'll examine the somewhat easier process of decoding suppose we received the string of bits shown in the preceding section how would we transform it back into characterswe can use kind of binary tree called huffman tree figure shows the huffman tree for the code just discussed the characters in the message appear in the tree as leaf nodes the higher their frequency in the messagethe higher up they appear in the tree the number outside each circle is the frequency the numbers outside non-leaf nodes are the sums of the frequencies of their children we'll see later why this is important how do we use this tree to decode the messagefor each character you start at the root if you see bityou go left to the next nodeand if you see bityou go right try it with the code for awhich is you go leftthen rightthen left againandmirabile dictuyou find yourself on the node this is shown by the arrows in figure
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'll base our approach on the node and tree classes in the tree java program in listing (although routines that are specific to search treeslike find()insert()and delete(are no longer relevanthere is the algorithm for constructing the tree make node object (as seen in tree javafor each character used in the message for our susie example that would be nine nodes each node has two data itemsthe character and that character' frequency in the message table provides this information for the susie message make tree object for each of these nodes the node becomes the root of the tree insert these trees in priority queue (as described in they are ordered by frequencywith the smallest frequency having the highest priority that iswhen you remove treeit' always the one with the least-used character
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 larger and largerand there will be fewer and fewer of them when there is only one tree left in the queueit is the huffman tree and you're done figures and show how the huffman tree is constructed for the susie message alf bt sp lf sp sp lf figure growing the huffman treepart lf sp sp lf
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 simplified alphabet that has only uppercase letters with characters is is and so on up to zwhich is space is and linefeed is we number these characters so their numerical codes run from to (this is not compressed codejust simplification of the ascii codethe normal way characters are stored in the computer our code table would be an array of cells the index of each cell would be the numerical value of the character for for band so on the contents of the cell would be the huffman code for the corresponding character not every cell contains
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 the end of the coded message until it' complete creating the huffman code how do we create the huffman code to put into the code tablethe process is like decoding message we start at the root of the huffman tree and follow every possible path to leaf node as we go along the pathwe remember the sequence of left and right choicesrecording for left edge and for right edge when we arrive at the leaf node for characterthe sequence of and is the huffman code for that character we put this code into the code table at the appropriate index number this process can be handled by calling method that starts at the root and then calls itself recursively for each child eventuallythe paths to all the leaf nodes will be explored and the code table will be complete
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 key values greater than (or equal toa trees perform searchesinsertionsand deletions in (log ntime nodes represent the data objects being stored in the tree edges are most commonly represented in program by references to node' children (and sometimes to its parenttraversing tree means visiting all its nodes in some order the simplest traversals are preorderinorderand postorder an unbalanced tree is one whose root has many more left descendents than right descendantsor vice versa searching for node involves comparing the value to be found with the key value of nodeand going to that node' left child if the key search value is lessor to the node' right child if the search value is greater insertion involves finding the place to insert the new node and then changing child field in its new parent to refer to it an inorder traversal visits nodes in order of ascending keys preorder and postorder traversals are useful for parsing algebraic expressions when node has no childrenit can be deleted by setting the child field in its parent to null when node has one childit can be deleted by setting the child field in its parent to point to its child when node has two childrenit can be deleted by replacing it with its successor the successor to node can be found by finding the minimum node in the subtree whose root is ' right child in deletion of node with two childrendifferent situations arisedepending on whether the successor is the right child of the node to be deleted or one of the right child' left descendants
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 coding in the huffman code the characters that appear most frequently are coded with the fewest bitsand those that appear rarely are coded with the most bits questions these questions are intended as self-test for readers answers may be found in appendix insertion and deletion in tree require what big time binary tree is search tree if every non-leaf node has children whose key values are less than (or equal tothe parent every left child has key less than the parent and every right child has key greater than (or equal tothe parent in the path from the root to every leaf nodethe key of each node is greater than (or equal tothe key of its parent node can have maximum of two children true or falsenot all trees are binary trees in complete binary tree with nodesand the root considered to be at level how many nodes are there at level subtree of binary tree always has root that is child of the main tree' root root unconnected to the main tree' root fewer nodes than the main tree sibling with the same number of nodes in the java code for treethe and the are generally separate classes
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 values greater than the average whose behavior is unpredictable in which the root or some other node has many more left children than right childrenor vice versa that is shaped like an umbrella inserting node starts with the same steps as node suppose node has successor node then must have key that is larger than but smaller than or equal to in binary tree used to represent mathematical expressionwhich of the following is not truea both children of an operator node must be operands following postorder traversalno parentheses need to be added following an inorder traversalparentheses must be added in pre-order traversal node is visited before either of its children if tree is represented by an arraythe right child of node at index has an index of true or falsedeleting node with one child from binary search tree involves finding that node' successor huffman tree is typically used to text which of the following is not true about huffman treea the most frequently used characters always appear near the top of the tree normallydecoding message involves repeatedly following path from the root to leaf
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 trees what percentage would you say are seriously unbalanced create uml activity diagram (or flowchartfor you old-timersof the various possibilities when deleting node from binary search tree it should detail the three cases described in the text include the variations for left and right children and special cases like deletion of the root for examplethere are two possibilities for case (left and right childrenboxes at the end of each path should describe how to do the deletion in that situation use the binary tree workshop applet to delete node in every possible situation programming projects writing programs to solve the programming projects helps to solidify your understanding of the material and demonstrates how the concepts are applied (as noted in the introductionqualified instructors may obtain completed solutions to the programming projects on the publisher' web site start with the tree java program (listing and modify it to create binary tree from string of letters (like aband so onentered by the user each letter will be displayed in its own node construct the tree so that all the nodes that contain letters are leaves parent nodes can contain some non-letter symbol like make sure that every parent node has exactly two children don' worry if the tree is unbalanced note that this will not be search treethere' no quick way to find given node you may end up with something like thise
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 and two of the one-node trees as its children then keep adding one-node trees from the array to this larger tree don' worry if it' an unbalanced tree you can actually store this intermediate tree in the array by writing over cell whose contents have already been added to the tree the routines find()insert()and delete()which apply only to search treescan be deleted keep the displaytree(method and the traversals because they will work on any binary tree expand the program in programming project to create balanced tree one way to do this is to make sure that as many leaves as possible appear in the bottom row you can start by making three-node tree out of each pair of onenode treesmaking new node for the root this results in forest of threenode trees then combine each pair of three-node trees to make forest of seven-node trees as the number of nodes per tree growsthe number of trees shrinksuntil finally there is only one tree left againstart with the tree java program and make tree from characters typed by the user this timemake complete tree--one that is completely full except possibly on the right end of the bottom row the characters should be ordered from the top down and from left to right along each rowas if writing letter on pyramid (this arrangement does not correspond to any of the three traversals we discussed in this thusthe string abcdefghij would be arranged as one way to create this tree is from the top downrather than the bottom up as in the previous two programming projects start by creating node which will be the root of the final tree if you think of the nodes as being numbered in the same order the letters are arrangedwith at the rootthen any node numbered has left child numbered * and right child numbered * + you might use recursive routine that makes two children and then calls itself for each child the nodes don' need to be created in the same order they are arranged on the tree as in the previous programming projectsyou can jettison the search-tree routines from the tree class
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 generatedtraversals of the tree will yield the prefixinfixand postfix equivalents of the algebraic expression the infix version will need parentheses to avoid generating ambiguous expressions in the inorder(methoddisplay an opening parenthesis before the first recursive call and closing parenthesis after the second recursive call write program to implement huffman coding and decoding it should do the followingaccept text messagepossibly of more than one line create huffman tree for this message create code table encode the message into binary decode the message from binary back to text if the message is shortthe program should be able to display the huffman tree after creating it the ideas in programming projects and might prove helpful you can use string variables to store binary numbers as arrangements of the characters and don' worry about doing actual bit manipulation unless you really want to
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 as arrayssorted arraysand linked listsperform one or the other of these activities slowly thusbinary search trees might appear to be the ideal data storage structure unfortunatelyordinary binary search trees suffer from troublesome problem they work well if the data is inserted into the tree in random order howeverthey become much slower if data is inserted in already-sorted order ( or inversely sorted order ( when the values to be inserted are already ordereda binary tree becomes unbalanced with an unbalanced treethe ability to quickly find (or insert or deletea given element is lost this explores one way to solve the problem of unbalanced treesthe red-black treewhich is binary search tree with some added features there are other ways to ensure that trees are balanced we'll mention some at the end of this and examine severaltrees and - treesin trees and external storage in factas we'll see in that operations on tree correspond in surprising way to operations on red-black tree our approach to the discussion we'll explain insertion into red-black trees little differently than we have explained insertion into other data structures red-black trees are not trivial to understand because of this and also because of multiplicity of trees experimenting with the workshop applet rotations inserting new node deletion the efficiency of red-black trees red-black tree implementation other balanced trees
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 tree with the code shown in howeverthe concepts you learn about here will aid your understanding of trees and are themselves quite interesting conceptual for our conceptual understanding of red-black treeswe will be aided by the rbtree workshop applet we'll describe how you can work in partnership with the applet to insert new nodes into tree including human into the insertion routine certainly slows it down but also makes it easier for the human to understand how the process works searching works the same way in red-black tree as it does in an ordinary binary tree on the other handinsertion and deletionwhile based on the algorithms in an ordinary treeare extensively modified accordinglyin this we'll be concentrating on the insertion process top-down insertion the approach to insertion that we'll discuss is called top-down insertion this means that some structural changes may be made to the tree as the search routine descends the tree looking for the place to insert the node another approach is bottom-up insertion this involves finding the place to insert the node and then working back up through the tree making structural changes bottom-up insertion is less efficient because two passes must be made through the tree balanced and unbalanced trees before we begin our investigation of red-black treeslet' review how trees become unbalanced fire up the binary tree workshop applet from (not this rbtree appletuse the fill button to create tree with only one node then insert series of nodes whose keys are in either ascending or descending order the result will be something like that in figure the nodes arrange themselves in line with no branches because each node is larger than the previously inserted oneevery node is right childso all the nodes are on one side of the root the tree is maximally unbalanced if you inserted items in descending orderevery node would be the left child of its parentand the tree would be unbalanced on the other side
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 this situation the speed of searching is reduced to ( )instead of (lognas it is for balanced tree searching through , items in such an unbalanced tree would require an average of , comparisonswhereas for balanced tree with random insertions it requires only for presorted data you might just as well use linked list in the first place data that' only partly sorted will generate trees that are only partly unbalanced if you use the binary tree workshop applet from to attempt to generate trees with nodesyou'll see that some of them are more unbalanced than othersas shown in figure although not as bad as maximally unbalanced treethis situation is not optimal for searching times in the binary tree workshop applettrees can become partially unbalancedeven with randomly generated databecause the amount of data is so small that even short run of ordered numbers will have big effect on the tree alsoa very small or very large key value can cause an unbalanced tree by not allowing the insertion of many nodes on one side or the other of its node root of for exampleallows only two more nodes to be inserted to its left
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 the tree is unbalanced balance to the rescue to guarantee the quick (log nsearch times tree is capable ofwe need to ensure that our tree is always balanced (or at least almost balancedthis means that each node in tree needs to have roughly the same number of descendents on its left side as it has on its right in red-black treebalance is achieved during insertion (and also deletionbut we'll ignore that for the momentas an item is being insertedthe insertion routine checks that certain characteristics of the tree are not violated if they areit takes corrective actionrestructuring the tree as necessary by maintaining these characteristicsthe tree is kept balanced red-black tree characteristics what are these mysterious tree characteristicsthere are twoone simple and one more complicatedthe nodes are colored during insertion and deletionrules are followed that preserve various arrangements of these colors
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 yang howevercolors are convenient labels data fieldwhich can be boolean (isredfor example)is added to the node class to embody this color information in the rbtree workshop appletthe red-black characteristic of node is shown by its border color the center coloras it was in the binary tree workshop applet in the preceding is simply randomly generated data field of the node when we speak of node' color in this we'll almost always be referring to its red-black border color in the figures (except the screenshot of figure we'll show black nodes with solid black border and red nodes with white border (nodes are sometimes shown with no border to indicate that it doesn' matter whether they're black or red red-black rules when inserting (or deletinga new nodecertain ruleswhich we call the red-black rulesmust be followed if they're followedthe tree will be balanced let' look briefly at these rules every node is either red or black the root is always black if node is redits children must be black (although the converse isn' necessarily true every path from the root to leafor to null childmust contain the same number of black nodes the "null childreferred to in rule is place where child could be attached to non-leaf node in other wordsit' the potential left child of node with right childor the potential right child of node with left child this will make more sense as we go along the number of black nodes on path from root to leaf is called the black height another way to state rule is that the black height must be the same for all paths from the root to leaf these rules probably seem completely mysterious it' not obvious how they will lead to balanced treebut they dosome very clever people invented them copy them onto sticky noteand keep it on your computer you'll need to refer to them often in the course of this
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 same keythis presents slight problem in red-black trees it' important that nodes with the same key are distributed on both sides of other nodes with the same key that isif keys arrive in the order you want the second to go to the right of the first oneand the third to go to the left of the first one otherwisethe tree becomes unbalanced distributing nodes with equal keys could be handled by some kind of randomizing process in the insertion algorithm howeverthe search process then becomes more complicated if all items with the same key must be found it' simpler to outlaw items with the same key in this discussion we'll assume duplicates aren' allowed fixing rule violations suppose you see (or are told by the appletthat the color rules are violated how can you fix things so your tree is in compliancethere are twoand only twopossible actions you can takeyou can change the colors of nodes you can perform rotations in the appletchanging the color of node means changing its red-black border color (not the center colora rotation is rearrangement of the nodes thatone hopesleaves the tree more balanced at this point such concepts probably seem very abstractso let' become familiar with the rbtree workshop appletwhich can help to clarify things using the rbtree workshop applet figure shows what the rbtree workshop applet looks like after some nodes have been inserted (it may be hard to tell the difference between red and black node borders in the figurebut they should be clear on color monitor there are quite few buttons in the rbtree applet we'll briefly review what they doalthough at this point some of the descriptions may be bit puzzling
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 workshop appletand also when you press the start buttonyou'll see that tree with only one node is created because an understanding of red-black trees focuses on using the red-black rules during the insertion processit' more convenient to begin with the root and build up the tree by inserting additional nodes to simplify future operationsthe initial root node is always given value of you select your own numbers for subsequent insertions the ins button the ins button causes new node to be createdwith the value that was typed into the number boxand then inserted into the tree (at least this is what happens if no color flips are necessary see the section on the flip button for more on this possibility notice that the ins button does complete insertion operation with one pushmultiple pushes are not required as they were with the binary tree workshop applet in the preceding it' therefore important to type the key value before pushing the button the focus in the rbtree applet is not on the process of finding the place
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 buttonthis deletion takes place immediately after the first pushmultiple pushes are not required the del button and the ins button use the basic insertion algorithms--the same as those in the tree workshop applet this is how the work is divided between the applet and the userthe applet does the insertionbut it' (mostlyup to the user to make the appropriate changes to the tree to ensure the red-black rules are followed and the tree thereby becomes balanced the flip button if there is black parent with two red childrenand you place the red arrow on the parent by clicking on the node with the mousethen when you press the flip buttonthe parent will become red and the children will become black that isthe colors are flipped between the parent and children you'll learn later why such color exchange is desirable if you try to flip the rootit will remain blackso as not to violate rule but its children will change from red to black the rol button the rol button carries out left rotation to rotate group of nodesfirst singleclick the mouse to position the arrow at the topmost node of the group to be rotated for left rotationthe top node must have right child then click the button we'll examine rotations in detail later the ror button the ror button performs right rotation position the arrow on the top node to be rotatedmaking sure it has left childthen click the button the / button the / button changes red node to blackor black node to red single-click the mouse to position the red arrow on the nodeand then push the button (this button changes the color of single nodedon' confuse it with the flip buttonwhich changes three nodes at once
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 violation occurred where' the find buttonin red-black treesa search routine operates exactly as it did in the ordinary binary search trees described in the preceding it starts at the rootandat each node it encounters (the current node)it decides whether to go to the left or right child by comparing the key of the current node with the search key we don' include find button in the rbtree applet because you already understand this process and our attention will be on manipulating the red-black aspects of the tree experimenting with the workshop applet now that you're familiar with the rbtree buttonslet' do some simple experiments to get feel for what the applet does the idea here is to learn to manipulate the applet' controls later you'll use these skills to balance the tree experiment inserting two red nodes press start to clear any extra nodes you'll be left with the root nodewhich always has the value insert new node with value smaller than the rootsay by typing the number into the number box and pressing the ins button adding this node doesn' cause any rule violationsso the message continues to say tree is red-black correct insert second node that' larger than the rootsay the tree is still red-black correct it' also balancedthere are the same number of nodes on the right of the only non-leaf node (the rootas there are on its left the result is shown in figure notice that newly inserted nodes are always colored red (except for the rootthis is not an accident inserting red node is less likely to violate the red-black rules than inserting black one this is becauseif the new red node is attached to black oneno rule is broken it doesn' create situation in which there are two red nodes together (rule )and it doesn' change the black height in any of the paths (rule of courseif you attach new red node to red noderule will be violated howeverwith any luck this will happen only half the time whereasif it were possible to add new black nodeit would always change the black height for its pathviolating rule
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 clicking it with the mouse this node will be the top node in the rotation now perform right rotation by pressing the ror button the nodes all shift to new positionsas shown in figure arrow figure following right rotation in this right rotationthe parent or top node moves into the place of its right childthe left child moves up and takes the place of the parentand the right child moves down to become the grandchild of the new top node notice that the tree is now unbalancedmore nodes appear to the right of the root than to the left alsothe message indicates that the red-black rules are violatedspecifically rule (the root is always blackdon' worry about this problem yet insteadrotate the other way position the red arrow on which is now the root (the arrow should already point to after the previous rotationclick the rol button to rotate left the nodes will return to the position of figure
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 flip is necessary wheneverduring the insertion processa black node with two red children is encountered the red arrow should already be positioned on the black parent (the root node)so click the flip button the root' two children change from red to black ordinarilythe parent would change from black to redbut this is special case because it' the rootit remains black to avoid violating rule now all three nodes are black the tree is still red-black correct now click the ins button again to insert the new node figure shows the result if the newly inserted node has the key value figure colors flippednew node inserted the tree is still red-black correct the root is blackthere' no situation in which parent and child are both redand all the paths have the same number of black nodes (twoadding the new red node didn' change the red-black correctness experiment an unbalanced tree now let' see what happens when you try to do something that leads to an unbalanced tree in figure one path has one more node than the other this isn' very unbalancedand no red-black rules are violatedso neither we nor the red-black algorithms need to worry about it howeversuppose that one path differs from another by two or more levels (where level is the same as the number of nodes along the pathin this case the red-black rules will always be violatedand we'll need to rebalance the tree insert into the tree of figure you'll see the message errorparent and child are both red rule has been violatedas shown in figure
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 / button the node becomes black the good news is we fixed the problem of both parent and child being red the bad news is that now the message says errorblack heights differ the path from the root to node has three black nodes in itwhile the path from the root to node has only two thusrule is violated it seems we can' win this problem can be fixed with rotation and some color changes how to do this will be the topic of later sections more experiments experiment with the rbtree workshop applet on your own insert more nodes and see what happens see if you can use rotations and color changes to achieve balanced tree does keeping the tree red-black correct seem to guarantee an (almostbalanced treetry inserting ascending keys ( and then restart with the start button and try descending keys ( ignore the messageswe'll see what they mean later these are the situations that get the ordinary binary search tree into trouble can you still balance the treethe red-black rules and balanced trees try to create tree that is unbalanced by two or more levels but is red-black correct as it turns outthis is impossible that' why the red-black rules keep the tree balanced if one path is more than one node longer than anotherit must either
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 is child that non-leaf node might havebut doesn' (that isa missing left child if the node has right childor vice versa thusin figure the path from to to the right child of (its null childhas only one black nodewhich is not the same as the paths to and which have two this arrangement violates rule although both paths to leaf nodes have the same number of black nodes black height is null child of black height is null child of black height is black height is figure path to null child the term black height is used to describe the number of black nodes from the root to given node in figure the black height of is of is still of is and so on rotations to balance treeyou need to physically rearrange the nodes if all the nodes are on the left of the rootfor exampleyou need to move some of them over to the right side this is done using rotations in this section we'll learn what rotations are and how to execute them rotations must do two things at once
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 if the rotation didn' maintain valid binary search treeit wouldn' be of much usebecause the search algorithmas we saw in the preceding relies on the search-tree arrangement note that color rules and node color changes are used only to help decide when to perform rotation fiddling with the colors doesn' accomplish anything by itselfit' the rotation that' the heavy hitter color rules are like rules of thumb for building house (such as "exterior doors open inward")while rotations are like the hammering and sawing needed to actually build it simple rotations in experiment we tried rotations to the left and right those rotations were easy to visualize because they involved only three nodes let' clarify some aspects of this process what' rotatingthe term rotation can be little misleading the nodes themselves aren' rotatedit' the relationship between them that changes one node is chosen as the "topof the rotation if we're doing right rotationthis "topnode will move down and to the rightinto the position of its right child its left child will move up to take its place remember that the top node isn' the "centerof the rotation if we talk about car tirethe top node doesn' correspond to the axle or the hubcapit' more like the topmost part of the tire tread the rotation we described in experiment was performed with the root as the top nodebut of course any node can be the top node in rotationprovided it has the appropriate child mind the children you must be sure thatif you're doing right rotationthe top node has left child otherwisethere' nothing to rotate into the top spot similarlyif you're doing left rotationthe top node must have right child the weird crossover node rotations can be more complicated than the three-node example we've discussed so far click startand thenwith already at the rootinsert nodes with the following valuesin this order
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 node now we'll try rotation place the arrow on the root (don' forget this!and press the ror button all the nodes move the follows the upand the follows the down but what' thisthe has detached itself from the whose right child it wasand become instead the left child of some nodes go upsome nodes go downbut the moves across the result is shown in figure the rotation has caused violation of rule we'll see how to fix this problem later in the original position of figure athe is called an inside grandchild of the top node (the is an outside grandchild the inside grandchildif it' the child of the node that' going up (which is the left child of the top node in right rotationis always disconnected from its parent and reconnected to its former grandparent it' like becoming your own uncle (although it' best not to dwell too long on this analogy
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 color flip message the resulting arrangement is shown in figure figure subtree motion during rotation
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 moves across to become the left child of the entire subtree of which is the root moves down you'll see the errorroot must be black messagebut you can ignore it for the moment you can flip back and forth by alternately pressing ror and rol with the arrow on the top node do this and watch what happens to the subtreesespecially the one with as its root in figure the subtrees are encircled by dotted triangles note that the relations of the nodes within each subtree are unaffected by the rotation the entire subtree moves as unit the subtrees can be larger (have more descendantsthan the three nodes we show in this example no matter how many nodes there are in subtreethey will all move together during rotation human beings versus computers at this pointyou've learned pretty much all you need to know about what rotation does to cause rotationyou position the arrow on the top node and then press ror or rol of coursein real red-black tree insertion algorithmrotations happen under program controlwithout human intervention notice however thatin your capacity as human beingyou could probably balance any tree just by looking at it and performing appropriate rotations whenever node has lot of left descendants and not too many right onesyou rotate it rightand vice versa unfortunatelycomputers aren' very good at "just lookingat pattern they work better if they can follow few simple rules that' what the red-black scheme providesin the form of color coding and the four color rules inserting new node now you have enough background to see how red-black tree' insertion routine uses rotations and the color rules to maintain the tree' balance
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 nodes is node that has caused rule violation (sometimes refers to newly inserted nodeand sometimes to the child node when parent and child have redred conflict is particular node is the parent of is the grandparent of (the parent of pon the way down the tree to find the insertion pointyou perform color flip whenever you find black node with two red children ( violation of rule sometimes the flip causes red-red conflict ( violation of rule call the red child and the red parent the conflict can be fixed with single rotation or double rotationdepending on whether is an outside or inside grandchild of following color flips and rotationsyou continue down to the insertion point and insert the new node after you've inserted the new node xif is blackyou simply attach the new red node if is redthere are two possibilitiesx can be an outside or inside grandchild of you perform two color changes (we'll see what they are in momentif is an outside grandchildyou perform one rotationand if it' an inside grandchildyou perform two this restores the tree to balanced state now we'll recapitulate this preview in more detail we'll divide the discussion into three partsarranged in order of complexity color flips on the way down rotations after the node is inserted rotations on the way down if we were discussing these three parts in strict chronological orderwe would examine part before part howeverit' easier to talk about rotations at the bottom of the tree than in the middleand operations and are encountered more frequently than operation so we'll discuss before color flips on the way down the insertion routine in red-black tree starts off doing essentially the same thing it does in an ordinary binary search treeit follows path from the root to the place
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 the insertion routine proceeding down the treegoing left or right at each nodesearching for the place to insert new node to make sure the color rules aren' brokenit needs to perform color flips when necessary here' the ruleevery time the insertion routine encounters black node that has two red childrenit must change the children to black and the parent to red (unless the parent is the rootwhich always remains blackhow does color flip affect the red-black rulesfor conveniencelet' call the node at the top of the trianglethe one that' red before the flipp for parent we'll call ' left and right children and this arrangement is shown in figure ax figure bp color flip black heights unchanged figure shows the nodes after the color flip the flip leaves unchanged the number of black nodes on the path from the root on down through to the leaf or null nodes all such paths go through pand then through either or before the fliponly is blackso the triangle (consisting of px and adds one black node to each of these paths after the flipp is no longer blackbut both and areso again the triangle contributes one black node to every path that passes through it so color flip can' cause rule to be violated color flips are helpful because they make red leaf nodes into black leaf nodes this makes it easier to attach new red nodes without violating rule
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 before we continue down the path to insert the new node we can correct the situation with rotationas we'll soon see the root situation what about the rootremember that color flip of the root and its two children leaves the rootas well as its childrenblack this color flip avoids violating rule does this affect the other red-black rulesclearlythere are no red-to-red conflicts because we've made more nodes black and none red thusrule isn' violated alsobecause the root and one or the other of its two children are in every paththe black height of every path is increased the same amount--that isby thusrule isn' violated either finallyjust insert it after you've worked your way down to the appropriate place in the treeperforming color flips (and rotationsif necessary on the way downyou can then insert the new node as described in the preceding for an ordinary binary search tree howeverthat' not the end of the story rotations after the node is inserted the insertion of the new node may cause the red-black rules to be violated thereforefollowing the insertionwe must check for rule violations and take appropriate steps remember thatas described earlierthe newly inserted nodewhich we'll call xis always red may be located in various positions relative to and gas shown in figure remember that node is an outside grandchild if it' on the same side of its parent that is of its parent that isx is an outside grandchild if either it' left child of and is left child of (figure )or it' right child of and is right child of (figure dconverselyx is an inside grandchild if it' on the opposite side of its parent that is of its parent (figures and cthe multiplicity of what we might call "handed(left or rightvariations shown in figure is one reason the red-black insertion routine is so complex to program
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 can be arranged in only three major ways (not counting the handed variations already mentionedeach possibility must be dealt with in different way to preserve red-black correctness and thereby lead to balanced tree we'll list the three possibilities briefly and then discuss each one in detail in its own section figure shows what they look like remember that is always red is black is red and is an outside grandchild of is red and is an inside grandchild of you might think that this list doesn' cover all the possibilities we'll return to this question after we've explored these three
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 parent is blackthere' no red-to-red conflict (rule and no addition to the number of black nodes (rule thusno color rules are violated we don' need to do anything else the insertion is complete possibility is red and is outside if is red and is an outside grandchildwe need single rotation and some color changes let' set this up with the rbtree workshop applet so we can see what we're talking about start with the usual at the rootand insert and you'll need to do color flip before you insert the now insert which is xthe new node figure shows the resulting tree the message on the workshop applet says errorparent and child both redso we know we need to take some action
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 topin the direction that raises ( this is right rotation in the example as you've learnedto switch colorsput the arrow on the node and press the / button to rotate rightput the arrow on the top node and press ror when you've completed the three stepsthe workshop applet will inform you that the tree is red/black correct it' also more balanced than it wasas shown in figure in this examplex was an outside grandchild and left child there' symmetrical situation when the is an outside grandchild but right child try this by creating the tree (with color flips when necessaryfix it by changing the colors of and and rotating left with at the top againthe tree is balanced possibility is red and is inside if is red and is an inside grandchildwe need two rotations and some color changes to see this one in actionuse the rbtree workshop applet to create the tree
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 the grandparent node ( at the topas we did in possibility the inside grandchild ( moves across rather than upso the tree is no more balanced than before (try thisthen rotate backwith at the topto restore it different solution is needed the trick when is an inside grandchild is to perform two rotations rather than one the first changes from an inside grandchild to an outside grandchildas shown in figures and now the situation is similar to possibility and we can apply the same rotationwith the grandparent at the topas we did before the result is shown in figure acolor change color change rotation rotation figure is red and is an inside grandchild
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 with ' parent at the top (not the grandparentthe parent is )in the direction that raises ( left rotation in this example rotate again with ' grandparent ( at the topin the direction that raises ( right rotationthe rotations and recoloring restore the tree to red-black correctness and also balance it (as much as possibleas with possibility there is an analogous case in which is the right child of rather than the left what about other possibilitiesdo the three post-insertion possibilities we just discussed really cover all situationssupposefor examplethat has sibling sthe other child of this scenario might complicate the rotations necessary to insert but if is blackthere' no problem inserting (that' possibility if is redboth its children must be black (to avoid violating rule it can' have single child that' black because the black heights would be different for and the null child howeverwe know is redso we conclude that it' impossible for to have sibling unless is red another possibility is that gthe grandparent of phas child uthe sibling of and the uncle of againthis scenario would complicate any necessary rotations howeverif is blackthere' no need for rotations when inserting xas we've seen so let' assume is red then must also be redotherwisethe black height going from to would be different from that going from to but black parent with two red children is flipped on the way downso this situation can' exist either thusthe three possibilities just discussed are the only ones that can exist (except thatin possibilities and can be right or left child and can be right or left childwhat the color flips accomplished suppose that performing rotation and appropriate color changes caused other violations of the red-black rules to appear further up the tree you can imagine situations in which you would need to work your way all the way back up the treeperforming rotations and color switchesto remove rule violations fortunatelythis situation can' arise using color flips on the way down has eliminated the situations in which rotation could introduce any rule violations further up the tree it ensures that one or two rotations will restore red-black correctness in
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 down rotations on the way down now we'll discuss the last of the three operations involved in inserting nodemaking rotations on the way down to the insertion point as we notedalthough we're discussing this operation lastit actually takes place before the node is inserted we've waited until now to discuss it only because it was easier to explain rotations for just-installed node than for nodes in the middle of the tree in the discussion of color flips during the insertion processwe noted that color flip can cause violation of rule ( parent and child can' both be redwe also noted that rotation can fix this violation on the way down there are two possibilitiescorresponding to possibility and possibility during the insertion phase described earlier the offending node can be an outside grandchildor it can be an inside grandchild (in the situation corresponding to possibility no action is required outside grandchild firstwe'll examine an example in which the offending node is an outside grandchild by "offending node,we mean the child in the parent-child pair that caused the red-red conflict start new tree with the nodeand insert the following nodes and you'll need to do color flips when inserting and now try to insert node with the value you'll be told you must do flipof and its children and you press the flip button the flip is carried outbut now the message says errorparent and child are both redreferring to and its child the resulting tree is shown in figure the procedure used to fix this rule violation is similar to the post-insertion operation with an outside grandchilddescribed earlier we must perform two color switches and one rotation so we can discuss this in the same terms we did when inserting nodewe'll call the node at the top of the triangle that was flipped (which is in this casex this looks little oddbecause we're used to thinking of as the node being insertedand here it' not even leaf node howeverthese on-the-way-down rotations can take place anywhere within the tree the parent of is ( in this case)and the grandparent of --the parent of --is ( in this casewe follow the same set of rules we did under possibility discussed earlier
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 the way down suddenlythe tree is balancedit has also become pleasantly symmetrical this appears to be bit of miraclebut it' only the result of following the color rules now the node with value can be inserted in the usual way because the node it connects to is blackthere' no complexity about the insertion one color flip (at is necessary figure shows the tree after is inserted inside grandchild if is an inside grandchild when red-red conflict occurs on the way downtwo rotations are required to set it right this situation is similar to the inside grandchild in the post-insertion phasewhich we called possibility
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 ins again in this situation is is and is as shown in figure change color rotate change color rotate figure inside grandchild on the way down
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 the topin the direction that raises (right in this examplenow you can insert the color flip changes and to black as you insert it the result is shown in figure this concludes the description of how tree is kept red-black correctand therefore balancedduring the insertion process deletion as you may recallcoding for deletion in an ordinary binary search tree is considerably harder than for insertion the same is true in red-black treesbut in additionthe deletion process isas you might expectcomplicated by the need to restore redblack correctness after the node is removed in factthe deletion process is so complicated that many programmers sidestep it in various ways one approachas with ordinary binary treesis to mark node as deleted without actually deleting it any search routine that finds the node knows not to tell anyone about it this solution works in many situationsespecially if deletions are not common occurrence in any casewe're going to forgo discussion of the deletion process you can refer to appendix "further reading,if you want to pursue it the efficiency of red-black trees like ordinary binary search treesa red-black tree allows for searchinginsertionand deletion in (log ntime search times should be almost the same in the red-black tree as in the ordinary tree because the red-black characteristics of the tree aren' used during searches the only penalty is that the storage required for each node is increased slightly to accommodate the red-black color ( boolean variablemore specificallyaccording to sedgewick (see appendix )in practice search in red-black tree takes about log comparisonsand it can be shown that the search cannot require more than *log comparisons
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 ordinary binary tree because in most applications there will be more searches than insertions and deletionsthere is probably not much overall time penalty for using red-black tree instead of an ordinary tree of coursethe advantage is that in red-black tree sorted data doesn' lead to slow (nperformance red-black tree implementation if you're writing an insertion routine for red-black treesall you need to do (irony intendedis to write code to carry out the operations described in the preceding sections as we notedshowing and describing such code is beyond the scope of this book howeverhere' what you'll need to think about you'll need to add red-black field (which can be type booleanto the node class you can adapt the insertion routine from the tree java program (listing in on the way down to the insertion pointcheck if the current node is black and its two children are both red if sochange the color of all three (unless the parent is the rootwhich must be kept blackafter color flipcheck that there are no violations of rule if soperform the appropriate rotationsone for an outside grandchildtwo for an inside grandchild when you reach leaf nodeinsert the new node as in tree javamaking sure the node is red check again for red-red conflictsand perform any necessary rotations perhaps surprisinglyyour software need not keep track of the black height of different parts of the tree (although you might want to check this during debuggingyou need to check only for violations of rule red parent with red childwhich can be done locally (unlike checks of black heightsrule which would require more complex bookkeepingif you perform the color flipscolor changesand rotations described earlierthe black heights of the nodes should take care of themselves and the tree should remain balanced the rbtree workshop applet reports black-height errors only because the user is not forced to carry out the insertion algorithm correctly other balanced trees the avl tree is the earliest kind of balanced tree it' named after its inventorsadelson-velskii and landis in avl trees each node stores an additional piece of datathe difference between the heights of its left and right subtrees this difference may
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 performed to equalize their heights the algorithm then moves up and checks the node aboveequalizing heights if necessary this check continues all the way back up to the root search times in an avl tree are (lognbecause the tree is guaranteed to be balanced howeverbecause two passes through the tree are necessary to insert (or deletea nodeone down to find the insertion point and one up to rebalance the treeavl trees are not as efficient as red-black trees and are not used as often the other important kind of balanced tree is the multiway treein which each node can have more than two children we'll look at one version of multiway treesthe - treein the next one problem with multiway trees is that each node must be larger than for binary tree because it needs reference to every one of its children summary it' important to keep binary search tree balanced to ensure that the time necessary to find given node is kept as short as possible inserting data that has already been sorted can create maximally unbalanced treewhich will have search times of (nin the red-black balancing schemeeach node is given new characteristica color that can be either red or black set of rulescalled red-black rulesspecifies permissible ways that nodes of different colors can be arranged these rules are applied while inserting (or deletinga node color flip changes black node with two red children to red node with two black children in rotationone node is designated the top node right rotation moves the top node into the position of its right childand the top node' left child into its position left rotation moves the top node into the position of its left childand the top node' right child into its position color flipsand sometimes rotationsare applied while searching down the tree to find where new node should be inserted these flips simplify returning the tree to red-black correctness following an insertion
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 effect on average performanceand avoids worst-case performance when the data is already sorted questions these questions are intended as self-test for readers answers may be found in appendix balanced binary search tree is desirable because it avoids slow performance when data is inserted in balanced treea the tree may need to be restructured during searches the paths from the root to all the leaf nodes are about the same length all left subtrees are the same height as all right subtrees the height of all subtrees is closely controlled true or falsethe red-black rules rearrange the nodes in tree to balance it null child is child that doesn' exist but will be created next child with no children of its own one of the two potential children of leaf node where an insertion will be made non-existent left child of node with right child (or vice versa which of the following is not red-black rulea every path from root to leafor to null childmust contain the same number of black nodes if node is blackits children must be red the root is always black all three are valid rules
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 "crossovernode or subtree starts as and becomes or vice versa which of the following is not truerotations may need to be made before node is inserted after node is inserted during search for the insertion point when searching for node with given key color flip involves changing the color of and an outside grandchild is on the opposite side of its parent that its parent is of its sibling on the same side of its parent that its parent is of its parent one which is the left descendant of right descendant (or vice versad on the opposite side of its parent that its sibling is of their grandparents true or falsewhen one rotation immediately follows anotherthey are in opposite directions two rotations are necessary when the node is an inside grandchild and the parent is red the node is an inside grandchild and the parent is black the node is an outside grandchild and the parent is red the node is an outside grandchild and the parent is black true or falsedeletion in red-black tree may require some readjustment of the tree' structure
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 situation to insert new node use the rbtree workshop applet to set up all the situations depicted in experiment and follow the instructions for insertion do enough insertions to convince yourself that if red-black rules and are followed exactlyrule will take care of itself note because no code was shown in this it hardly seems fair to include any programming projects if you want serious challengeimplement red-black tree you might start with the tree java program (listing from
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 that can have up to four children and three data items per node trees are interesting for several reasons firstthey're balanced trees like red-black trees they're slightly less efficient than red-black trees but easier to program secondand most importantthey serve as an easy-to-understand introduction to -trees -tree is another kind of multiway tree that' particularly useful for organizing data in external storage (external means external to main memoryusually this is disk drivea node in -tree can have dozens or hundreds of children we'll discuss external storage and -trees at the end of this introduction to trees in this section we'll look at the characteristics of trees later we'll see how workshop applet models - tree and how we can program tree in java we'll also look at the surprisingly close relationship between trees and red-black trees figure shows small tree each lozenge-shaped node can hold onetwoor three data items efficiency of trees - trees external storage
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 contained in given node for non-leaf nodesthree arrangements are possiblea node with one data item always has two children node with two data items always has three children node with three data items always has four children in shorta non-leaf node must always have one more child than it has data items orto put it symbolicallyif the number of child links is and the number of data items is dthen = + this critical relationship determines the structure of trees leaf nodeby contrasthas no childrenbut it can nevertheless contain onetwoor three data items empty nodes are not allowed because tree can have nodes with up to four childrenit' called multiway tree of order you may wonder why tree isn' called - tree can' node have only one childas nodes in binary trees cana binary tree (described in "binary trees,and "red-black trees"can be thought of as multiway tree of order because each node can have up to two children howeverthere' difference (besides the maximum number of childrenbetween binary trees and - trees in binary treea node can have up to two child links single linkto its left or to its right childis also perfectly permissible the other link has null value
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 -node figure -node -node -node nodes in tree tree organization for convenience we number the data items in link from to and the child links from to as shown in figure the data items in node are arranged in ascending key orderby convention from left to right (lower to higher numbersan important aspect of any tree' structure is the relationship of its links to the key values of its data items in binary treeall children with keys less than the node' key are in subtree rooted in the node' left childand all children with keys larger than or equal to the node' key are rooted in the node' right child in tree the principle is the samebut there' more to itall children in the subtree rooted at child have key values less than key all children in the subtree rooted at child have key values greater than key but less than key
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 comparing equal keys nodes with keys less than figure nodes with keys between and nodes with keys between and nodes with keys greater than keys and children refer back to the tree in figure as in all treesthe leaves are all on the same level (the bottom rowupper-level nodes are often not fullthat isthey may contain only one or two data items instead of three alsonotice that the tree is balanced it retains its balance even if you insert sequence of data in ascending (or descendingorder the tree' self-balancing capability results from the way new data items are insertedas we'll see in moment searching tree finding data item with particular key is similar to the search routine in binary tree you start at the root andunless the search key is found thereselect the link that leads to the subtree with the appropriate range of values for exampleto search for the data item with key in the tree in figure you start at the root you search the root but don' find the item because is larger than you go to child which we will represent as (remember that child is on the right because the numbering of children and links starts at on the left you don' find the data item in this node eitherso you must go to the next child herebecause is greater than but less than you go again to child this time you find the specified item in the link insertion new data items are always inserted in leaveswhich are on the bottom row of the tree if items were inserted in nodes with childrenthe number of children would need to be changed to maintain the structure of the treewhich stipulates that there should be one more child than data items in node
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 data item with key being inserted into tree abefore insertion bafter insertion shifted right inserted figure insertion with no splits insertion may involve moving one or two other items in node so the keys will be in the correct order after the new item is inserted in this example the had to be shifted right to make room for the node splits insertion becomes more complicated if full node is encountered on the path down to the insertion point when this happensthe node must be split it' this splitting process that keeps the tree balanced the kind of tree we're discussing here is often called top-down tree because nodes are split on the way down to the insertion point let' name the data items in the node that' about to be split aband here' what happens in split (we assume the node being split is not the rootwe'll examine splitting the root later newempty node is created it' sibling of the node being splitand is placed to its right data item is moved into the new node
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 has been transformed into two -nodes to be inserted this node is split abefore insertion moves up bafter insertion stays put new node moves right inserted figure splitting node notice that the effect of the node split is to move data up and to the right it is this rearrangement that keeps the tree balanced here the insertion required only one node splitbut more than one full node may be encountered on the path to the insertion point when this is the casethere will be multiple splits splitting the root when full root is encountered at the beginning of the search for the insertion pointthe resulting split is slightly more complicateda new root is created it becomes the parent of the node being split second new node is created it becomes sibling of the node being split
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 old one thusthe overall height of the tree is increased by one another way to describe splitting the root is to say that -node is split into three -nodes the root is split to be inserted abefore insertion moves up bafter insertion new root node stays put moves right new right node inserted figure splitting the root following node splitthe search for the insertion point continues down the tree in figure the data item with key of is inserted into the appropriate leaf splitting on the way down notice thatbecause all full nodes are split on the way downa split can' cause an effect that ripples back up through the tree the parent of any node that' being split
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 of insertions into an empty tree there are four node splitstwo of the root and two of leaves ab figure insertions into tree the tree workshop applet operating the tree workshop applet provides quick way to see how trees work when you start the appletyou'll see screen similar to figure
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 the tree may not look very full with nodesbut more nodes require more levelswhich won' fit in the display the find button you can watch the applet locate data item with given key by repeatedly clicking the find button when promptedtype in the appropriate key thenas you click the buttonwatch the red arrow move from node to node as it searches for the item messages will say something like went to child number as we've seenchildren are numbered from to from left to rightwhile data items are numbered from to after little practice you should be able to predict the path the search will take search involves examining one node on each level the applet supports maximum of four levelsso any item can be found by examining maximum of four nodes within each non-leaf nodethe algorithm examines each data itemstarting on the leftto see if it matches the search key orif notwhich child it should go to next in leaf node it examines each data item to see if it matches the search key if it can' find the specified item in the leaf nodethe search fails
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 boxto be inserted in the tree the algorithm first searches for the appropriate node if it encounters full node along the wayit splits that node before continuing experiment with the insertion process watch what happens when there are no full nodes on the path to the insertion point this process is straightforward then try inserting at the end of path that includes full nodeeither at the rootat the leafor somewhere in between watch how new nodes are formed and the contents of the node being split are distributed among three different nodes the zoom button one of the problems with trees is that there are great many nodes and data items just few levels down the tree workshop applet supports only four levelsbut there are potentially nodes on the bottom leveleach of which can hold up to three data items displaying so many items at once on one row is not practicalso the applet shows only some of themthe children of selected node (to see the children of another nodeyou click on itwe'll discuss that in moment to see zoomed-out view of the entire treeclick the zoom button figure shows what you'll see figure the zoomed-out view
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 gray these colors are hard to distinguish on the figureyou'll need to view the applet on your color monitor to make sense of the display using the zoom button to toggle back and forth between the zoomed-out and zoomed-in views allows you to see both the big picture and the details andwe hopeput the two together in your mind viewing different nodes in the zoomed-in view you can always see all the nodes in the top two rowsthere' only onethe rootin the top rowand only four in the second row below the second row things get more complicated because there are too many nodes to fit on the screen on the third row on the fourth howeveryou can see any node you want by clicking on its parentor sometimes its grandparent and then its parent blue triangle at the bottom of node shows where child is connected to node if node' children are currently visiblethe lines to the children can be seen running from the blue triangles to them if the children aren' currently visiblethere are no linesbut the blue triangles indicate that the node nevertheless has children if you click on the parent nodeits childrenand the lines to themwill appear by clicking the appropriate nodesyou can navigate all over the tree for convenienceall the nodes are numberedstarting with at the root and continuing up to for the node on the far right of the bottom row the numbers are displayed to the upper right of each nodeas shown in figure nodes are numbered whether they exist or notso the numbers on existing nodes probably won' be contiguous figure shows small tree with four nodes in the third row the user has clicked on node so its two childrennumbered and are visible if the user clicks on node its childrennumbered and will appearas shown in figure these figures show how to switch among different nodes in the third row by clicking nodes in the second row to switch nodes in the fourth rowyou'll need to click first on grandparent in the second row and then on parent in the third row during searches and insertions with the find and ins buttonsthe view will change automatically to show the node currently being pointed to by the red arrow
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 the split node are going to go then press ins again to see whether you're right as the tree gets larger you'll need to move around it to see all the nodes click on node to see its children (and their childrenand so onif you lose track of where you areuse the zoom key to see the big picture
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 fill upanother root splitleading to five levelswould be necessaryand this is impossible because the applet supports only four levels you can insert the most items by deliberately inserting them into nodes that lie on paths with no full nodesso that no splits are necessary of coursethis is not reasonable procedure with real data for random data you probably can' insert more than about items into the applet the fill button allows only to minimize the possibility of overflow java code for tree in this section we'll examine java program that models tree we'll show the complete tree java program at the end of the section this program is relatively complexand the classes are extensively interrelatedso you'll need to peruse the entire listing to see how it works there are four classesdataitemnodetree and tree app we'll discuss them in turn the dataitem class objects of the dataitem class represent the data items stored in nodes in real-world program each object would contain an entire personnel or inventory recordbut here there' only one piece of dataof type longassociated with each dataitem object the only actions that objects of this class can perform are to initialize themselves and display themselves the display is the data value preceded by slash/ (the display routine in the node class will call this routine to display all the items in node the node class the node class contains two arrayschildarray and itemarray the first is four cells long and holds references to whatever children the node might have the second is three cells long and holds references to objects of type dataitem contained in the node note that the data items in itemarray comprise an ordered array new items are addedor existing ones removedin the same way they would be in any ordered array (as described in "arrays"items may need to be shifted to make room to insert new item in orderor to close an empty cell when an item is removed
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 paid in increased node size various small utility routines are provided in the node class to manage the connections to child and parent and to check if the node is full and if it is leaf howeverthe major work is done by the finditem()insertitem()and removeitem(routineswhich handle individual items within the node they search through the node for data item with particular keyinsert new item into the nodemoving existing items if necessaryand remove an itemagain moving existing items if necessary don' confuse these methods with the find(and insert(routines in the tree classwhich we'll look at next display routine displays node with slashes separating the data itemslike /// / /or / don' forget that in javareferences are automatically initialized to null and numbers to when their object is createdso class node doesn' need constructor the tree class an object of the tree class represents the entire tree the class has only one fieldrootof type node all operations start at the rootso that' all tree needs to remember searching searching for data item with specified key is carried out by the find(routine it starts at the root and at each node calls that node' finditem(routine to see whether the item is there if soit returns the index of the item within the node' item array if find(is at leaf and can' find the itemthe search has failedso it returns - if it can' find the item in the current nodeand the current node isn' leaffind(calls the getnextchild(methodwhich figures out which of node' children the routine should go to next inserting the insert(method starts with code similar to find()except that it splits full node if it finds one alsoit assumes it can' failit keeps lookinggoing to deeper and deeper levelsuntil it finds leaf node at this point the method inserts the new data item into the leaf (there is always room in the leafotherwisethe leaf would have been split splitting the split(method is the most complicated in this program it is passed the node that will be split as an argument firstthe two rightmost data items are removed
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 parent of the node being split it may be pre-existing parentor if the root is being splitit will be the newly created root node assume the three data items in the node being split are called aband item is inserted in this parent node if necessarythe parent' existing children are disconnected and reconnected one position to the right to make room for the new data item and new connections the newright node is connected to this parent (refer to figures and now the focus shifts to the newright node data item is inserted in itand child and child which were previously disconnected from the node being splitare connected to it the split is now completeand the split(routine returns the tree app class in the tree app classthe main(routine inserts few data items into the tree it then presents character-based interface for the userwho can enter to see the treei to insert new data itemand to find an existing item here' some sample interactionenter first letter of showinsertor finds level= child= / level= child= / / level= child= / / enter first letter of showinsertor findf enter value to find found enter first letter of showinsertor findi enter value to insert enter first letter of showinsertor finds level= child= / level= child= /level= child= / / enter first letter of showinsertor findi enter value to insert enter first letter of showinsertor finds
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 firstthen its first child and the subtree of which the first child is the rootthen the second child and its subtreeand so on the output shows two items being inserted and the second of these caused node (the root' child to split figure depicts the tree that results from these insertionsfollowing the final press of the key child child figure level child level child sample output of the tree java program the complete tree java program listing shows the complete tree java programincluding all the classes just discussed as with most object-oriented programsit' probably easiest to start by examining the big picture classes first and then work down to the detail-oriented classes in this program this order is tree apptree nodedataitem listing the tree java program /tree java /demonstrates tree /to run this programc>java tree app import java io *///////////////////////////////////////////////////////////////class dataitem
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 numitemsprivate node parentprivate node childarray[new node[order]private dataitem itemarray[new dataitem[order- ]//connect child to this node public void connectchild(int childnumnode childchildarray[childnumchildif(child !nullchild parent this//disconnect child from this nodereturn it public node disconnectchild(int childnumnode tempnode childarray[childnum]childarray[childnumnullreturn tempnode/public node getchild(int childnumreturn childarray[childnum]/public node getparent(return parent/public boolean isleaf(
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 nodefor(int = <order- ++/if found/otherwiseif(itemarray[ =null/return - breakelse if(itemarray[jddata =keyreturn jreturn - /end finditem /public int insertitem(dataitem newitem/assumes node is not full numitems++/will add new item long newkey newitem ddata/key of new item for(int =order- >= --/start on right/examine items if(itemarray[ =null/if item nullcontinue/go left one cell else /not null/get its key long itskey itemarray[jddataif(newkey itskey/if it' bigger itemarray[ + itemarray[ ]/shift it right else itemarray[ + newitem/insert new item
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 numitems--/one less item return temp/return item /public void displaynode(/format "//for(int = <numitemsj++itemarray[jdisplayitem()/"/ system out println("/")/final "///end class node ///////////////////////////////////////////////////////////////class tree private node root new node()/make root node /public int find(long keynode curnode rootint childnumberwhile(trueif(childnumber=curnode finditem(key!- return childnumber/found it else ifcurnode isleaf(return - /can' find it else /search deeper
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 getnextchild(curnodedvalue)/end if(node is fullelse ifcurnode isleaf(/if node is leafbreak/go insert /node is not fullnot leafso go to lower level else curnode getnextchild(curnodedvalue)/end while curnode insertitem(tempitem)/insert new dataitem /end insert(/public void split(node thisnode/split the node /assumes node is full dataitem itembitemcnode parentchild child int itemindexitemc thisnode removeitem()/remove items from itemb thisnode removeitem()/this node child thisnode disconnectchild( )/remove children child thisnode disconnectchild( )/from this node
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(itemb)/item to parent int parent getnumitems()/total itemsfor(int = - >itemindexj--/move parent' /connections node temp parent disconnectchild( )/one child parent connectchild( + temp)/to the right /connect newright to parent parent connectchild(itemindex+ newright)/deal with newright newright insertitem(itemc)/item to newright newright connectchild( child )/connect to and newright connectchild( child )/on newright /end split(//gets appropriate child of node during search for value public node getnextchild(node thenodelong thevalueint /assumes node is not emptynot fullnot leaf int numitems thenode getnumitems()for( = <numitemsj++/for each item in node /are we lessifthevalue thenode getitem(jddata return thenode getchild( )/return left child /end for /we're greaterso
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 each child of this node int numitems thisnode getnumitems()for(int = <numitems+ ++node nextnode thisnode getchild( )if(nextnode !nullrecdisplaytree(nextnodelevel+ )else return/end recdisplaytree(//end class tree ///////////////////////////////////////////////////////////////class tree app public static void main(string[argsthrows ioexception long valuetree thetree new tree ()thetree insert( )thetree insert( )thetree insert( )thetree insert( )thetree insert( )
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 getint()int found thetree find(value)if(found !- system out println("found "+value)else system out println("could not find "+value)breakdefaultsystem out print("invalid entry\ ")/end switch /end while /end main(//public static string getstring(throws ioexception inputstreamreader isr new inputstreamreader(system in)bufferedreader br new bufferedreader(isr)string br readline()return //public static char getchar(throws ioexception string getstring()
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 probably seem like entirely different entities howeverit turns out that in certain sense they are completely equivalent one can be transformed into the other by the application of few simple rulesand even the operations needed to keep them balanced are equivalent mathematicians would say they were isomorphic you probably won' ever need to transform tree into red-black treebut equivalence of these structures casts additional light on their operation and is useful in analyzing their efficiency historicallythe tree was developed firstlater the red-black tree evolved from it transformation from to red-black tree can be transformed into red-black tree by applying three rulesas shown in figure transform any -node in the tree into black node in the red-black tree this is shown in figure transform any -node into child node and parent nodeas shown in figure the child node has two children of its owneither and or and the parent has one other childeither or it doesn' matter which item becomes the child and which the parent the child is colored red and the parent is colored black
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 tree and the corresponding red-black tree obtained by applying these transformations dotted lines surround the subtrees that were made from -nodes and -nodes the red-black rules are automatically satisfied by the transformation check that this is sotwo red nodes are never connectedand there is the same number of black nodes on every path from root to leaf (or null childyou can say that -node in tree is equivalent to parent with red child in red-black treeand -node is equivalent to parent with two red children it follows that black parent with black child in red-black tree does not represent -node in treeit simply represents -node with another -node child similarlya black parent with two black children does not represent -node
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 splits in red-black tree the two balancing methods are color flips and rotations -node splits and color flips as you descend tree searching for the insertion point for new nodeyou split each -node into two -nodes in red-black tree you perform color flips how are these operations equivalentin figure we show -node in tree before it is splitfigure shows the situation after the split the -node that was the parent of the -node becomes -node in figure we show the red-black equivalent to the tree in the dotted line surrounds the equivalent of the -node color flip results in the redblack tree of figure now nodes and are black and is red thus and its parent form the equivalent of -nodeas shown by the dotted line this is the same -node formed by the node split in figure