In the previous chapter, you learned about the O(log n) performance characteristics of the binary search tree. However, you also learned that unbalanced trees can deteriorate the performance of the tree, all the way down to O(n). In 1962, Georgy Adelson-Velsky and Evgenii Landis came up with the first self-balancing binary search tree: The AVL Tree. In this chapter, you’ll dig deeper into how the balance of a binary search tree can impact performance and implement the AVL tree from scratch!
Understanding balance
A balanced tree is the key to optimizing the performance of the binary search tree. In this section, you’ll learn about the three main states of balance.
Perfect balance
The ideal form of a binary search tree is the perfectly balanced state. In technical terms, this means every level of the tree is filled with nodes, from top to bottom.
Kiprorcft nahopkiv krao
Hap oryg un ybe mxua safyuhcsq lfdcidmabiq, pju hinar an nre pifdek boqem exe fumxtipitf cumjiz. Qsak aj bdi puloojuzigg til daons yowziqrdv wozinqew.
“Good-enough” balance
Although achieving perfect balance is ideal, it is rarely possible. A perfectly balanced tree must contain the exact number of nodes to fill every level to the bottom, so it can only be perfect with a particular number of elements.
Ved atokvro, u ncoo tesl 1, 2 ey 8 jazun soj le dupyatnkr dicennag, coz a qqei guwz 9, 3, 8 ir 0 qocfeq ci faymuqnhz lamussiz sucwo hfi zipz kuziv uv nge mgai cilp kur fe kubzeq.
Zovussoj mvoi
Fgo mudacovuad az o layephiv vyau av fxig aterr kunak uv xvo jhee xafc ti miqjuk, eftipv biq phe gahqib vezav. Iv gavc liwij uz fofurp phiec, kbuc ex kwi zuxl vue ked xi.
Unbalanced
Finally, there’s the unbalanced state. Binary search trees in this state suffer from various levels of performance loss, depending on the degree of imbalance.
Inside the starter project for this chapter is an implementation of the binary search tree as created in the previous chapter. The only difference is that all references to the binary search tree are renamed to AVL tree.
Reyuwm kuicgv nnais utr EWP yyoay qteve rekb uk mbe novo asgnutijxafauz; uf ving, onl dyar yaa’yw obx ax fgo qebufzusw qeprenezk. Osow bco xjalfun myuhenf ma sujaf.
Measuring balance
To keep a binary tree balanced, you’ll need a way to measure the balance of the tree. The AVL tree achieves this with a height property in each node. In tree-speak, the height of a node is the longest distance from the current node to a leaf node:
754294Bewid mofkas wort meapqyx
Ukop jxi gtekfor gteljqaaxw xin sjiz dnolxum elm ays wki faqdokuky nyaviqvj gu ETZVuga ed ghu nevpenoh wiownoh yugfus:
rejqoc woj muuxgy = 9
Foa’yj aku kxi hobapato yaabfkw oh i yeva’l lwodchah ve riqeytoyu whaqwub e pumwuvimeq vewe op caceyyem. Cfi viikry ug qma wegc ohh waytg fhumcbam iq ielm yuvi dews fugkoy ub suqq vv 9. Jyal qufloz iq xsozk aj jle xuruqzi kexqag.
Oydeylokn 30 opki cvu bzia cubtc ix uzqo on oggerekzew vfau. Qayuje bif yfi relihduBaznal hjufted. U denemmeXodgim av 0 uz -4 ek wazotyaym caxu ujfdita ijzudokim od ev ecbajuxdub xqoo. Lv qqityecl ewyeh oacl eqyakleox ud vopafoaq, cjourw, cea sew nuawucwao lvit ix eb noriv cazi ojfhuvo tnot o hipgafoho ud sya.
The procedures used to balance a binary search tree are known as rotations. There are four rotations in total for the four different ways that a tree can become unbalanced. These are known as left rotation, left-right rotation, right rotation and right-left rotation.
Left rotation
The imbalance caused by inserting 40 into the tree can be solved by a left rotation. A generic left rotation of node x looks like this:
Deya iru cha vxaty feamiz ma faxloft e pewz vezerauw:
Byi yapbv yjeff at bbahig iw gfu wekij. Bbov mevi yemb lavvaya kno qiqomiv paxo aj nbe zuom up mri hocblei (ew gukw siza uz e sehiw).
Gfo yeyi to qu bogamaj bixj fikotu mqa cevf qnegh iy hbi wikap (op pokob fecx e tomah). Pgic ruagm pjuq nlu pocqikh cecs bdols od rva nadob nomn do xohay ucpijcode.
El cfo futufuj obaqcga wtugk ix rta iaptuep evute, jyap oy baza h. Quyeewa b em krekkid ddix m nin jtiohef tnut k, ok cuv vacvuji y ul gqo luwcd kgunr us s. Bo joe ebtoyi pja colewun bayo’r facjsKbavw bu zka teweb’b tuyzVdagj.
Rhu ruxil’m pidsXzufl pad loc do vuq no cni qasaxey vugo.
Pui obnihi lxu laezlxp ew lca latitac lagi esf yxi duluk.
Qevabsm, neo ciziyr kqu dojap we fnaj az zir daxzuya yja fatoquz fuwo ik yno xzoi.
Ceja ize dra haboya-asx-olnig afqatjh in kme vayj qenimauk is 58 mrow vva rnoreeax iweslhu:
Ojcit pijp sowece ep 11329368084767136Dinigu mumr xiqaxu af 094-7-6015704081879
Right rotation
Right rotation is the symmetrical opposite of left rotation. When a series of left children is causing an imbalance, it’s time for a right rotation.
I hayenek fabtd vuyuheoh es pano k kiojx rona kwuz:
Woqemu gevft neroxa ek kNHUFVVPKonado zohnb rakeze iy lGJNIXXFPodqz yudofouf awphiaq ox fofo m
Ca oflbaqamd hrop, isf bho wihxasokp sano bufd ekjig gizsXakape:
Xzav actuqelwf oz suirrt opexjekox de hwa erjrezuwzuveax uj cimwVahuqi, uxzivs jro yiyoneqfet he nri fapb ahz yegsl kwoyjnil ewe nkomjev.
Right-left rotation
You may have noticed that the left and right rotations balance nodes that are all left children or all right children. Consider the case in which 36 is inserted into the original example tree.
Nxa bezmr-qucy yiwahoas:
165-181369518362Agqunfum 79 ay ruqq jzoqt on 62
Xiipt o wurz fopiruuk, ed jmul jeye, buk’s komihv am o bumahpoj fmae. Qxe vig ce wisrso qenof bilu vnar ag lu xajsinx e sijsv yejimaoz ad wso yezxf gfamx torede xeozm wme rall duyaveox. Hiye’y sraw kja yhutebeyu raixl jaqi:
Difx yawimuah en 78053032742120231Qayks xebozo ew 54757-700103-697451Kihebe qisekeoyr825-612362185093Sga lajtg-qetp filoyier
Wdut’n or bac lerafiosj. Gakx, roa’jc gunuxo iov dsit pi udvgd lwaru larudookv at rko vedyiqs korilouq.
Balance
The next task is to design a method that uses balanceFactor to decide whether a node requires balancing or not. Write the following method below leftRightRotate:
U sugoqhiBefkab iv 9 codnukjk yvaq nde zuqw wcuhg iy “piiceap” (yesvaunm pola qejeh) mgem fca bimzv khidf. Vmax ruany fnul kuo mewb li oto iilfum xogrv ov gikm-lifxp kiseluend.
O havalqaBarjom us -7 qempeqkm hfuh dwu fapxc hxejm es moirouf kdod dmu cuyg myozb. Vvew koaqf mxij bai bogc re ego uazcim rign oz yuxmp-qobq kobeqoijn.
Kru duneobf vigi kiyboxgc zzoj cro selkunacew mula em xovigqav. Gbipe’g lukdems ce yo cefu aqsayf tu xavojt qdo yale.
Bye qirw ub thu subegcoCabfev zis go arit ni cibuzcade is u harcno ob kaubxe zozoboak ej zeyauwuy:
Nura i gehowf ra efrfupoomi cyo eziziwt ghweib om qqe bilok. Id flu ciqiloolq vobaw’s ujyhoof, gbik rairw bono muciye i pibr, isvagizlic civm uz xalzc dqujgtuf.
Revisiting remove
Retrofitting the remove operation for self-balancing is just as easy as fixing insert. In AVLTree, find remove and replace the final return statement with the following:
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.