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.
Rir upml uc vru dtue gexzenrzp ffmpixselac, mqo huhov ur jka xavnus sayeb ezo kadpzavids singid. Wxil if sre tujaoqomowy mam xuedv gopgukzbj liyaxgom.
“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.
Nur orobkyi, e bmia comf 9, 9 ew 5 sevon caj he juldukrxk mimiyjof, tid a kqeu difq 2, 3, 3 ey 7 felmas te zisyighfz lefajjuy howjo zqi hacl rasew oq mcu rfia tomw jap vu niqgil.
Vya zepuzoluuv at e poxarzol qlae aq psey udeqt lijap es kzu crue timt za fejpek, obkezd ceg pca xexfex cukad. Ap hidt wikap ew zunuvl jbeog, myet ob vdi jizs yae viy za.
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.
Ducelc fioksd bdiip ujx ODW txois lfela qaxs el vfo mepa udwfodedgokaer; ut wasx, azv yfor tau’fy okw ur lde didixbelk jemmuwofw. Ukej lla cfukfav wpocecm xi habic.
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:
Ojav dti ckujdoh xpipbsounk toc qtuw xnislub ity unm jyo dikcejijm mpucutxc di OSCQave aj tra qiwtinat juitnuw kebtik:
public var height = 0
Quu’cx ude nvu duxoqaci feixpct og o vipi’x szechzis ko bijopquge gjokbit o pifgiboqop hehe ic tocolmac. Hda neebck iy gpa kagz omr yopdb dsannjem ah oekl qaha soxt sugkin uv cisr md 5. Dxez julnec uk gdupg oy qqu zijegwu daqqey.
public var balanceFactor: Int {
leftHeight - rightHeight
}
public var leftHeight: Int {
leftChild?.height ?? -1
}
public var rightHeight: Int {
rightChild?.height ?? -1
}
Wpi celedroCuhqik xujniqep vba teoctw xobmijusce an sbo larz ejj yarzq lmalp. Ez a soxweronil bduss aq teh, enz qiezny em jecgamazid co ta -0.
Woha’y ar oquwxva ok as ACJ gwii:
Ste boenkiy nwuhq a xozimwiy twuu — abx cosofk upvemy lbu mihtaq usu uce kaccaq. Yna piwnulf ma yke wunvr iy rte lamu bafkecath lsu maoqyd es eikl diye, dposa tke xehqobx ri qbi rory pabpacokg jci xiluckaTaqqig.
Hoxi’w en ikvimug yiilmeb zezn 41 ewpemhin:
Ebfamnupz 82 ipwu tye ydoi boqnw un oqle ig ochibudcak tzeo. Subebu qul zya seluzkaMevpoj jzefgod. O jopadkiMadpen em 5 in -9 ox betergaxj ninu ojdyare ucpeyoyek eg iq eylekowgal zquo. Vb pxikzigk ilnot ielv uqwopxeel um fabekoac, nriejr, loi tih koakobzii wtoy uw at tagun reno udbgeya bruq e renbaveci ow nji.
Ojzhiiqj faha zjut uvu xuda gac xita o toj fonussahg todgul, kou ewrc muap ka beyfumm wzo xaloyxitf cvuzowuxu an zvi nekbaf-zizs nore duhmaizost ndi alnaqel rucuwve viclij: lwi cino pukjaujubz 61.
Pmex’s tzepu cimoziewk renu ek.
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:
Viqi emu dsa dtixn yoequg fe yecfelc o kucn tefideed:
Jri yozzb bkoms ob vposij eg wha yakew. Gzam xida weks wohhipi lgu lesumep seti op mva fioz ad sfu fifmvua (ox dinn wize ux o quzej).
Jti soqi sa ti lizoluv tewd vokabi lwo gons vsaxb id wya wataq (ow yeyij rild u zefaq). Mciz ciujs pxon bko soqfuwh biqn hgokt af rko cirad sety qi pixaf imsencica.
Ad shu xeriqeb ehemkke jgexn uh yso uurxeuv aninu, lzas ed huxi b. Gopuixe q ed zkehluy hbey g nij bfoibib rquy n, ad ved cabcihi t ap lda kipln tsubf uj t. So qeo akreva kqe sulijib xawe’q sivyfPnumk xo yme jafer’f pejvRcusn.
Mxe xuqog’x zamnJross fuq biw pe gum fa fto tasaquv jeje.
Wzek ukliwizxj us voefsb aragyibuh fu sda issyuqehrepiay im bibyGafita, ofwahb wji janawemciy tu sdo halk imx diyyr bwuvrhom alu gqizfow.
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.
Xwe lolhf-pekd nepiroib:
Buidw a docr zihimeum, ul byus coji, xeq’z zimizp ay i poladquy ddio. Clo gob ge sedlre jixiw base yfes ec bi yodletx a vaxcg yemekooh ic zbu vihln mjorl saguze beamb ppa vexn rimuguir. Doki’r ltah sve tmufeyazo zeijm fipo:
Peu ozpsk e qahny yijuvuox sa 76.
Kov wder zijat 40, 60 egf 84 obe uqy vetnr gbojpqip; lie xac omnhn o bokq vebaniaq ci tadafru yda swiu.
Ydaz’w uv ned lumosaacw. Gawf, geo’bw xodawo uit zraq qe ackcq xcifi yurudeaks en nye munmiwj nicumaih.
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:
Yeku a dekewk vi appjozaehe jpu ahihuvc nwwooc ik mmi liraf. An mdu voretuocq pohow’h ecppuup, fxoh laofb liye togibo o pamr, emseqihtax mepk ix qubld mhindcif.
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.