0% found this document useful (0 votes)
16 views

Red Black Tree

Nothing

Uploaded by

sharmila11121311
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
16 views

Red Black Tree

Nothing

Uploaded by

sharmila11121311
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 17
Properties of red-black trees A red-black tree is «binary scar tee with one exe bit of storage per node: its ‘olor, wich canbe either RED oF BLACK. By costae the node colors on any Simple path from the rot oles re-black tres ensure thal no such pa is more than twice a long os any other, s0 tha the tee i approximately belanced, ‘child cr the parent of anode does not exist, the corresponding pointer atibute ‘of the noe contains the value NHL; We sal regard these NIL as being pointers 0 leaves (extemal nodes) of the binay sarc re and the normal, ey- bearing nodes a being intemal nes ofthe tee Aed:black we sa binary te tha satisfies the following red-black properties 1, Every node is ther redo black 3. very lal (Nt) is back 4. I anode ised then both its chien are black, 5. Forcach nade, all simple pts from the node to descendant leaves contain the 15.1() shows an example of areca te ‘As a matter of convenience in dealing with boundary conditions in red-back luce code, we use single sentinel o represent NIL (se page 238). Fors red black tree T, the sentinel Til can objet with the same attributes as an ordinary node tribute is BLACK, and its oer attributes ple righ td ey can take on arbitrary vals, As Figure 13.1(b) shows, ll pointers 0 St are replaced by pointers to the sentinel 7.1 We ute the setinel ro that we can teat @ NIL child of node x as an ondary node whose parent is <. Although we instead could ad x distinct sentinel nod in the te, so thatthe paca ofeach NIL is well define. that ap inl Tr to represea al the NiLs—all eaves and the root's parent. The vale ofthe attributes, lef right and hey ofthe sentinel are tnmtera, although we may set them during the ours a procedure for our convenience We generally confine ou interest to the internal nodes ofa red-black te, since they hod the key values. Inthe remainder of his chapter, we omit he leaves whe ‘we draw red-black tee, as shown in Figure 13.10). ‘We call the nimber of black nodes of any simple path from, but not inclading node x down toa leaf the Black-heght of the node. denoted bi). By propery 5. the notion of black-beigh is wel defined, since all descending simple paths fom the node have the same numberof black nse. We define the black-height of The following lemma shows why red-black tees make good search tres Lemma 13.1 A red-back: toe with n intemal nodes has eight at most 2Ig(0 +1), Proof Westartby showing thet the subtree rote at any node contains at last 2" — 1 internal nodes. We prove this claim by ication on the height of x. 1 contains at kast 29=) ~ 1'= 2° — 1 = 0 intemal nodes. For the inductive sep, onside aoe «that has positive height and isan intemal nde with 0 chien Each child has a blackceight of either B(x) ce D(x) ~ 1 depending on whether its colo is ed or black, espetively. Since the hoight ofa child of x is less than the eight of « self, we can apply the inductive hypothesis to conclude that ea child has a east 22°" —1 intemal nodes. Thus, the subtre rooted at x contins I) 41 = 2") intemal nodes, which proves Including the root, must be black. Consequently the black-height of the rect must newt Moving the | to the lefthamd side and taking Ig(n +1) > h/2,00h = 2igin + D. = Asan immite consequence ofthis lemma, we can implement the dynanic-et perations SEARCH, MINIMUM, MAXIMUM, SUCCESSOR, and PREDECESSOR in O(ign) time on fed-lack ees, since each ean run in Oh) time on binary ntsc of h in Cha any re on nodes of Chapter 12 would hae to be replaced by Til) lho RECINGERT and TREE-DeLere from Chapter 12 run in O gh the al ) ume when given ared-back tre a input, they do not in nary search tre will be ared-black tee, We however, hw to support these fo operations in including the root, must be black, Consequently, the black height ofthe root must Moving the Ito the lefthand sie and taking logarithms on both sides yields Igin-+ 1) > h/2,o0 = 2igtn + 1) . Asan immediate consequence of this lama, we can implement the éyamic-st operations SEARCH, MINIMUM, MAXIMUM, SUCCESSOR, und PREDECESSOR in Ollgn) time on rod-back tes, sine each ean run in O(h) tite on 8 bina Search woo of height (as shown in Chapter 12) and any ed-back re 0a nodes isa binary search tree with height OUigm). (Of course, references to Ni inthe by Tl.) Although the a sorts TREE-INSERT and TREE-DELETE from Chapter 12 run in OUigm) time ‘when given ared-black tee as input, they donot directly suppor the dyaamic-st operations INSERT and DELETE, sine they donot guarantee thatthe modifi bi algorithms of Chapter 12 would have 1 be reps hoster hos to spt these two operations in Og) time Bereaes rt Inthe style of Figure 13.12), daw the complete binary search re of eight 3 on ways such thatthe Back-heights ofthe resin re-black tees ae 2,3, nd 4 B12 Draw the red-back tee that resus afer TREE-INSERT is called on the te in Figure 13.1 with key 36. IF the inserted node is colored red, i the resulting tee a rel black tee? Whit ifs colored Mack ws Let us define a relaxed redclack tre as «binary search tee that satisfies re black properties 1, 3.4, and 5. In other worl, the root may be ether red or black, Consider a relaxed redblack wee whose foots ted. If we color the root of T black but make no other changes wo the esulling tee a red-lack tee? wis ‘Suppose that we “absorb” every red node in a rdeblack tre int its back paren so thatthe children ofthe red node become children ofthe black parent. (Ignore what happens tothe key.) What ae the possible degrees ofa black node after al its red chien are absorbed’? What can you say shout the depts ofthe leases of he resulting tr nas Sow that he longest simple ph from a node sina ri-back tre to a descendant leaf has length a most ice that of the shortest simple path from node to & ns ‘What isthe largest posible number of internal nodes in ared-ack tse with B7 Descrie a re-back tren keys that realizes the largest possible ratio of red in teal nodes to black inleral noes, Wha is this ratio? What re has the smallest wT Describe are-blak re on kes that relies the largest posible ratio of red in ternal nodes o black intemal oes. Whats this rio? What tre has the smallest possible tio, and whats the rato The seurch-te operations TREE-INSERT and TREE-DELETE, when run om a ed back re with Keys, tke O(lzn) time. Because they modify the tee, he result ‘ay violate the re: black propertice enumerated ia Secon 13.1. To restore these Properties, we must change the colors of some of the nodes inthe tre and also Change the pointer structure ‘We change the pointer structure through reaon, which i «cal operation i a search tre that preserves the binary-acarch-ree property. Figure 132 shows the two kinds of rotation: left sotations and right rotations, When we doa lef etation fra ode x, we assume that ts right chk ys ot Tlf x may be any node in the tee whose right child isnot T.nu. The left rotation “pivots” around the link rom to. Makes y the new root ofthe sure, with ys ef child and y's lef ld ass ight cil The pseudocode for LEFT-ROTATE assumes that x.right # Toland that the roots parent is Tal LerrRovare(T, Me 47 tar y's lef sabre imo sight subtree ink sport to y 8 belt nes : 1 put x on y's tre. The code for RIGHT-ROTATE is symmetric, Both LEFT-ROTATE and RIGHT. ovate mim in O(1) time, Only pointers are changed by a rotation all oher Bxereses B24 We can insert a node into a -node red-black tee in O(}g) tine. To do 50, we choos lor z red. (Exercise 13.31 asks you to explain why’ ‘ed rather than black.) To guaran © that the ed-black properties are preserved, we then call an auxiliary procedure RB-INSERT-FIXUP to recolor nodes and perform cations. The cll RB-INSERT(T, z) inserts node z, whose ey is assumed to have already boon filled in, into the ret-black tee 7 RB-INsERE(T. 1 y= Tait Teroot 3 while 2 Til 4 yes S Weckey Td 5 fRicTaavseuann(T.2.2 bf) 9 he ym Tae Minas rf 0 Se rm yok hit fA sp ese RB-TRANSHLANTUT yy) 1) RB-TwaNsaNtCT.c.9) 1B ylehp = y Although RB-DELETE contains almost rwice as many lies of pseudocode as TREE-DELETE, the (wo procedures have the same basic structure, You can find cach line of Taet-DeLere within RB-DELETE (with the changes of replacing NIL by Toni and replacing calls to TRANSPLANT by calls to RB-TRANSPLANT), executed under the sure conditions Here are the oer differences between the two procedures + Wen the te. Line I ses yo point node © when = has Fewer than two children and is therefore removed. When + Because node y's color might change the variable y-original-color stores y's color before any chang. es occur. Lines 2 and 10 set this variable immediaiely after assignments to y. When z has two children, then yz and node ‘moves into node 2's original position in the red-back tre; line 20 gives y the same color as z. We need 10 save y's original color in order to test it at the end of RB-DELETE; if t was back, then removing or moving y could cause Violations ofthe red: black propertics. ‘As discussed, we keep track of the node x that moves into aode y's erginal position. The assignment in lines 4, 7, and 11 set x to point o either y's only ikl or if y has no children, the sentinel Tn, (Recall rom Section 12.3 that y has no left child + Ba color before any changes occut. Lines 2 and 10 sei this variable immediately after assignments to y. When = has two children, then y # and node moves into rode 2's original position in the red-black re: ine 20 gives y the ause node y's color might change, the variable y-orig same color as :. We need 10 sive y's original color in order to test ita the end of RB-DELETE; if t was black, then remov » could cause Violations of the red-black properties, ck of the node x that moves into aode »'s original As discussed, we keep ti position. The assignments in lines 4, 7, and 11 set x to point to either y's only child or, if y has no children, the sentine! T-ni (Recall from Section 12.3 that y has no left child.) + Since node x moves ito node y's original position, the atrtute x,pis always ‘eto point to the original position i the tre of y's parent, even if xs, infact, the sentinel Zn. Unless 2 is y"s eriginal parent (which occurs aly when z has dren and its successor y is 2s right child), the assignment to, takes place in line 6 of RB-TRANSPLANT. (Observe that when RB-TRANSPL ANT is called in lines 5, 8, oF 14, the second parameter passed isthe same asx.) ‘When's original parent is 2, however, we do not want xp to point 0 ys rig inal parent, sine we are removing that node from the wee. Because node y will move up to take 's position inthe tee, setting x.p 10 y inline 13 causes xp to point wo the original positon of y's parent, even sfx = Toi ‘+ Finally, if node y was black, we might have induced one o more violations ofthe red-black properties, and so we call RB-DELETE-FINUP in line 22 10 restore the red-back properties. fy was red, the red-back properties stil hold ‘when is removed of moved, for the following re 1, No black-heights in the tree have changed 2. No red nodes have been made adjacent, Because y takes <'s place in the tree, along with 2°s cole, we eannot have two adjacent red nodes at y's new Position inthe tree, In addition, if y was nt zs right chil, then y's original ‘ight child x replaces inthe tee, Ify is red, then x must be black, and so replacing y by x cannot cause two red nodes to become adjacent 3, Since y could not have hoon the rot ft was red, the root remains black node y was black, three problems may arise, which the call of RB-DELETE= Fixvr will emedy, Fist if y had been the root and a red child of y beco nes the new roo, we have violated property 2. Second, if both x and x.p are red, then we have violated property 4, Third, moving y within the tee causes any simple path that previously contained y to have one fewer black node. Thus, property 5 is now violated by any ancestor of yin the ee. We can correct the violation ‘of property 5 by saying that node x, now accupying y's orginal position, hasan black. Thats, if we add Ito the count of black nodes on any sim hat contains x, then under this interpretation, property 5 holds. When we remove ‘or move the black node y, we “push” its blackness onto node x, The problem is hat now node x is nether rod nor black, thereby violating property 1. Instead, rode x is ether “doubly black” or “red-and-black,” and it contibutes either 2oF 1 respectively, t0 the count of black nodes on simpie paths containing ¥. The col ‘atibute of will sll be either RED (i x is red-and-black) oF BLACK (if is ‘doubly black) In other words, the extra black on node is reflected ins pointing to the node rather than inthe color atsibute rode « is ether “doubly black” or “red-and:-black,” and it contibutes either 2oF 1 respectively, 10 the count of black nodes on simple paths containing *. The co xicibute of » will stil be either RED (i is rod-and-black) or BLACK Gi x is ‘doubly black). In other words, the extra black on node is reflected inxs point tothe node rather than inthe color attibut ‘We can now sec the procedure RB-DELETE-FIXUP and examine how it restores the rede black properties tothe search tree RB-DELETE-FIXuP(T,x) 1 while x 4 Toot and x. color == BLACK 2 yee x.puleft ‘ it w.color == RED 5 w.color = BLACK Hesse 1 6 x.pcolor = RED Wowe | 7 LEFT-ROTATE(T, x.p) Wosse | 8 u ight Wease | 9 I w.letcolor == BLACK and w.right.color == BLACK 0 RED UW case? u x UW esse? 2 else If w.right.color == BLACK B waleft.color = BLACK Wowse3 4 w.color = RED Wesse 3 1s RiGitT-ROTATE(T. 1) case 3 16 w = xpurigh Wcase 3 r w.color = x.p.co Wcase4 1s xp.color = BLACK Wowse4 0 ight. color = BLACK Woase4 0 Lert-RovaTe(T, x.p) Mowe 2 x=Tr W eases 22 else (sume as then clause with “right” and “Left” exchanged) The procedure RB-DELETE-FIXUP restores properties 1, 2, and 4. Exercises 134-1 and 134-2 ask you to show thatthe procedure restores properties 2 and 4 and so in the reminder of this section, se shall focus om property I. The goal of the while lop in lines 1-22 isto move the extra black up the tree wat 1.x points toa red-and-black node, in which case we color x (singly) blak in line 23 X points to the rot, in which case we simply “remove” the extra black; of 3. having performed suitable rotations and reolorings, we ext the op. Within the while lop, + always points to a nonroot doubly black node. We determine in line 2 whether x isa left ehikl or aright child ofits parent xp. CWe have given the code forthe situation in which xis a left child; the station in Which x is right ehild—line 22—is symmetric.) We maintain a pointer w 10 pe sibling of x. Since node x is doubly black, node w cannot be T.nil, becatse ‘otherwise, the numberof blacks on the simple path from x.p to the singly black) leat w would be smaller than the number on the sn se path from x,p 0 The four cases” in the code appear in Figure 13.7. Before examining exch case in detail, le’ look more generally at how we can verify thatthe transformation in each of the cases preserves property 5. The key idea is that in each cas, the Jc nodes (including x's extra formation applied preserves the number of b Within the w determine inline 2 whether x isa let child o aright child of its parent xp. (We have given the code for the situation in which a left child: the situation i le loop, always points to a nonroot doubly black node, We which x is a right chld—line 22—is symmetric.) We maintain a pointer w to the sibling of x. Since node is doubly black, node w cannot be T:ni, because otherise, the number of blacks on the simple path from xp tothe (singly black) leaf w would be smaller than the number on the simple path from xp tox The four cases in the code appear in Figure 13.7. Before examining each case in detail, let's look more generally at how we cin verify thatthe transformation in each of the cases preserves property 5. The key idea is that in each case, the transformation applied preserves the number of black odes Gncling 3's extra black) from (and including) the oot of the subtree shown to each of the subtrees Bro... Thus, if property 5 holds prior to the transformation, it continues to hold afterward. For example, in Figure 13.7(a), which illustrates case I, the num ber of black nodes from the rot to either sublrce cor fis 3, both before and afer the transformation. (Again, remember that node x adds an extra black.) Similay the number of black nodes from the oot to any of y, 8, e, and £ is 2, both be fore and after the transformation. In Figure 13.7(b, de counting must involve the ‘value ¢ ofthe color stibute ofthe root ofthe subtree shown, which can be RED oF BLACK. If we define count(RED) = 0 and count(BLACk) = 1, then the number of black nodes from the root fo «is 2 + count(c), both before and afer the transformation. In this case, alter the transformation, the new node his color atte , but this node is really either red-and-black (if e = RE) or doubly black (ife = ALACK). You can verify the other cases similarly (we Exercise 13.45). Case 1: x's sibling wis red ‘Case | (lines 5-8 of RB-DELETE-FIXUP and Figure 13.7) occurs when node must have black children, we can switch the of the red-black properties. The new sibling of x, which is one of w's children black, and thus We have converted case I into case 2 the sibling of node x, is red, Since colors of wo and xp and then perform a le-rottion on x.p without viol Cases 2,3, and 4 occur when node w is black; they are distinguished by the colors of ws children, Case 2+ x's sibling w is Black, and both of w's children are black In case 2 (lines 10-11 of RE-DELETE-FIXUP and Figure 13.7(5), both of 1's children are black. Since w is also black, we take one black off both x and w leaving x with only one black and leaving w red. To compensate for removing «ne black fom x an w, we Would lke to ad an extra Black (0 £.p, which Was cxiginlly either red or black. We do so by repeating the while loop with x,p as the new nowde x. Observe tha if we enter ease 2 through case 1, the new node 3 is rd-and black, since the orginal x.p was red. Hence, the value ¢ ofthe color tribute ofthe new node ¥ i RED, and the loop terminates when i ests the loop condition, We thea color the new node « (singly) black in line 23, Case 3: x's sibling w is Black, w’s left child is red, and w's right child is Black Case 3 (lines 13-16 and Figure 13.2(€) occurs when w is black, its left child is red, and its right child is black. We can switch the colors of w and its lef Exercises B41 Argue that after executing RB-DELETE-PIXUP, the root ofthe tee must be black, B42 Argue tat if in RB-DELTE: both x and xp are rd, then property 4 is restored by the call o RB-DELETE-FIXUP(T. x)

You might also like