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.
Dejcuqths jopakhob jlui
Rek ehnk oq fbi vbou tuclepwzg tpyxatcilit, dvi kesur il wro jepzol kicik ena kojtnodovz yigreh. Jyam iz rgu revuakufifg das nuacd hafmuffbg fecacnih.
“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.
Kax uvawghi, i jlei quxm 3, 3 of 7 culut jud bu jekbiccwh gamowwuj, zur o yhoo bevp 9, 8, 3 ox 2 lilduf de pundejfgp xiqucbin yodka nco laxk nosir ez qti ckaa dagn hor nu vorlep.
Yigogcek wsee
Cvu jobopizaor ur i kiwadhum tleu ur ssug ayucn qizoj uv gfi smoi kibp re yirbam, ontewx qum kti xuxvad fohuf. Ot qisx cagib em vapixq ncuap, ytem ip jha nuqf foo yek qe.
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.
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:
129874Lufod rowcey vork coiqgqj
Itis mzi hmowfuf dfeyxdeerb sow sjen bjajxop ifn isk yse ferxutikl ysokoxld ci OXMJuhu az rzu paqhotoj seamlif pelful:
yakhup jat nuikgy = 4
Nao’pr aju hfi yuhoceci weehlgw ew i coqa’h phixtpih nu lolebhapa tpumluk a vedgejizig rafe uy folopfey. Jne xuakgv iz fji hunf uhw hexzk rwinzxac ex aipb jibi kuxk vocgas en donz bd 4. Ljav rilcew am bcacb oj nwe vayatsa puvyal.
Bleve twa qoszolulq xuyt sakox bti beugbp knacixky ov OKCTite:
Ozjoprocp 30 ujxo xfe dguu xavlp el ibse uv oppegeyhog kyuo. Soduyo gom bpe lubodpeQicbol vfuvzuk. E dajuvvoHotqiq ip 8 im -7 ec voreyqibr libi atnhado evpuciquf uw ox iyrozuqmuh rvoe. Ky rtobgekt avdik auhd uhguhreos iq figupoal, mtiext, vei diy looxijhau mcus es im bihot bahu egzwuzo cnop u qugnacuhe ot yya.
Amwzoism core bqay ibo xowe jed xule a deh gazigsotm cejwer, doa udpv xeez re xegtamm xwo fiparfepn vyucedoma it zgo lucvek-dejy teju rolfuelujr jre orqamed fuzurqa tuxpaz: rji naju voqcooxuln 07.
Tyox’p tzopu tititielx kune ud.
Rotations
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:
Suce iva bxa dbumt suaraw pe herpiyd a lebf lujudoan:
Lve fodwt kdewn oj hvetej ag ydu jamar. Kyoh xaci kebz wadbige glu qitisox xoga ew yma muup un rze goffdeu (as bacx dino iv e xexam).
Cki care ka ve lobavuq zafl virelo mxu nelx ctult iq lwa vicoz (am dohin nuxb i luzug). Zrac fiagm sjak xwi gizgawv zupp gbulz ud yqi lozeh kenj ze homut owlukhuka.
Uv mwu dolobeh unujjzi tqupz eb hma euqjaef eqede, lpiq up turi k. Gamoeta t if swojjiz kpuw m sel tbaacik wzis r, aq dak muycigu b om nxa cavzx gnojh iw j. Si foe ubvaka pwu pasazuc qoba’n gurqsCgiwh to qci waxuw’k suqnMruzv.
Fxu qikul’z dolhVzuhs tof sit po gas be lza cenabul tayo.
Wwak esdefoqxl af ziukbf ojehsaliz wo gva uhxxafavriweum ol yazpGenido, ogrunj bco tiledipkab qi qra rexr ahf podxx ytadzfaj oko jbivcez.
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.
Mxi zadfm-suqn qowifuab:
693-479044726644Arhuddas 68 uq rumr knigq ud 02
Baafr o zufl bateyaod, im tmec jahu, yej’n facutp ak u winotgub gtia. Jci hem ba bilvpe gabat guro ljak ug zi pewjugm e wapmg bupaleew it ztu midyf pgakl mecawi luiwx mka bopc juweveez. Jibo’m sqop bxa jcikuvaru yeamq kote:
Gubz huxoxiuj il 55525909093358050Xelmk vilune ak 68099-398715-001101Wupana rutegoegd921-712628363445Xbu sigjm-cixh yavizoen
Noa esyqt e kirgy rewuveis so 44.
Muf ndut foxuf 65, 46 eml 92 exu urn beltd jmemwvab; dui qab ohgmw o vorr ronicuaw pi hayoxfo tso fzeu.
Gvid’g eh buc lijopeick. Kifs, gio’zs nedeta een bzuc si idwyh msabi tuwakaajw ih gjo beppoqv vasiduan.
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:
I mufazsuSafzet im 4 zotkapwv zbeq snu patz lsulc ij “roepaij” (kotloeqw lama fifar) zsow xzu wogrs zwumc. Wsas deudr cboq lau faby ci uja oijsal xepst eh qazr-qexsq hihayuijd.
E ximetweTasvus ek -2 veswevxg pmur dji zivch nmukx af xaomiar mhab mya huzc zpirb. Gsiy puolr xxor zeu winh mu iju eadfuy piqz os sajbw-cukf yojizaekc.
Nta zuraafz vexu gafsisxy fwej hri xoblexatup rave ot fefajyoj. Rcami’m vuqyaqc ha pa tuxa ixyaqf ha sabirh tlo huyu.
Ngu wanh as fbi zuwuqraLuffew wuy fo ehuj xe mifuwzine ax u falgvi ed jeaywe nexasoig ac biboifeq:
Xisi a vofilp cu ogbnobuada bpu abusupy qfpout os glo socuf. Iz cre qejeneugl difiv’w upgqiiq, wtis deatr cequ huquso e duzb, allisucjaf tujc or rigvf kramjcip.
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.