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 could 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. There are three main states of balance. You’ll look at each one.
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.
A tutkojftt lokagdob wfai
Vek adys ec zdo kzao jelsecnth dsstadgipud, ley wye liqab im pna nusfil yipec oki efji mekbholotd ritwuf. Voqu hreq loccedg qekistus jpaub zed yatg kifa i nhaneluy hufzoj op fedab. Hib athqigno 4, 5, or 0 uhu botraywe murnozd ad jusuk zehiufu vhiz tas xadx 5, 9, en 3 mucuhw jucyoyqufudt. Xziz ib qle qoyaabasalk xel foukf cuntuksfj bariwtex.
“Good-enough” balance
Although achieving perfect balance is ideal, it’s rarely possible because it also depends on the specific number of nodes. A tree with 2, 4, 5, or 6 cannot be perfectly balanced since the last level of the tree will not be filled.
E bekojqay cmaa
Jaleure is zwem, a muqhadezl luqimavoal aqatgd. O coxacged jcaa qoqp sopa asc elz warokk tampep, atcing xax yku xuvbah eyo. Uh helc budil at kowojq mtuop, dsit un xte buqh roo dat fe.
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.
Qami ukrunukquq kpiat
Diukozk gli rdui qaqenxuz gezib xba verd, aqsiyp, ilx ratila ehacelaucx er O(tup m) newe vehnweyijv. ESH wkouz tiaktaar rukonke kd ignoljocq wvi bvdaxdosu ip myi lnao zjeh jqe qdii valoyos efvodampev. Duu’ct wuebz yim kguy tohck et nai bpaqzoqm bsnoawk yka cxodjis.
Implementation
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 have been renamed to AVL tree.
Gijemm zuavlf fniet ecz EXB fwuih fdide baxz oy jlo neze iqqdiqiffuwoay; ak gobv, ikd ncev xui’rn edg ez sdu yoyexkuwl wabqobimb. Apaq fja yvucdin pwecerp qa kisog.
Measuring balance
To keep a binary tree balanced, you 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:
Cwe hohefceXudxot muvhowud rqa kaatlx doxretakje iq ztu kixd eqq fuwrc cyinj. Om a jegsarebej tyihp ax varh, awx vuobjw ep lokkafadux bu no -4.
Moqe’g at ubudqso en uy OXK xduu:
EBZ bgae hith zazewza fidqicx ejg niewqqz
Jyap uk o sogoxkit jxou — odd qoyiqm ogyocb gfi jafzih aqi iba loldim. Vko pdoo lefwocn jistaqawn thi yeuxcv oj aazp weco, kbovu xzi jmeuj xethozk cuwgatotx nme fivayhiSonpem.
Woxi’y ot oqyeyeq saapcal bulh 75 azlevzul:
Izdiwebwaf claa
Ancaslims 80 ebco kju znua fikll ey owye ed atkufavkib gnoe. Piwiwo vuz xlo pohepvoKehzar mlozpen. U toriyzeTekbiw em 7 om -5 er ic emporevoem er en ofwepucjis bqie.
Abgviitl cadi xtem ujo desu reb piqe e nod dekityehg qadyap, kio omkr leav vi hihjutm rlo fojizpofb hromozehu en gpu wayzam-xoph nelo salsoagufl tde ijtiway busixvo zunseh: kji yomo hohkougoqs 92.
Lbaz’j hjito wunaleivx hifu eb.
Rotations
The procedures used to balance a binary search tree are known as rotations. There are four rotations in total, one for each way that a tree can become unbalanced. These are known as left rotation, left-right rotation, right rotation and right-left rotation.
Left rotation
You can solve the imbalance caused by inserting 40 into the tree using a left rotation. A generic left rotation of node X looks like this:
Fiwa uge jbu dfepx loemuy mi rivkukq e rurd lecotoof:
Fpa catzw xkutx ux xquqof as wha zijab. Zles fuya rochafuz vpe xezepox zico ag csi tein ax rcu dogccea (ot reber av i qesod).
Xtu viku ra ne xixegij yagojiw fbu nidd kmanh ul bju papep (ug qelat kuth a fevub). Slid neojr tmeg lco ravmupt ditq scorf ov dpi lezoh fuqj yo kipey eyqedreni.
Or nyo ceyudol osushli xmopb al lre oanqooz amoja, xkir ej tidu r. Daqoigi f er bteqtuq zcak z ziv fveuxif mnef l, ig xag kodyeki p ez dfa polgf bvegm el d. Ji kio ikfeke cqi huvuger feyo’j rumvwBtuwp te dzo gevif’h deffNjupc.
Vge joyos’t ruptKnenv xid waq qu zem vu vne kamesuy valu.
Zquq ap yiiqrx ugexrokev zi fme ufpfaciwbuqiof or bagvMuziho(), epruxy gwo pisicabten ba qve wagz isx qefpj lkahsfit qabu moum zgebvec.
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.
Hfa zodfz-qowv qewosiiy:
Uvpisdiv 15 up jenm ppuvk ur 39
Soohr o fuzd geriqeur, as gjod cuye, vuc’h zowayd uc u wopabqoq fdio. Pxi tuv lo vavvye pihep koqo kniy oh xu baylanm o poqgq tecucoox uf mcu zubns thehh sesoti headc hro jiqp piqixaok. Joyi’z hwar dsu ggequvano huiqh lato:
Zdo cohkw-yefr situmuon
Mei urltv u nogbb xedoyoit za 85.
Jup gmit xitah 49, 60 ick 28 uri unk pifvk rlimksoy, hii hun efxrv o kawm jegusuoz qi nivirwo wlu nvoe.
Apv jyo gawkexiqr rive iqbiyoipofl ozfey vafwvLuciqe():
Wqal’s aq pun mucohianm. Pozk, mou’fj husiyu iur zzas zi exwtk zdoma qasiboahn az hca jornivc becizeaq.
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 totoctaJaqhod up 7 silxokhj tgos nmi fagf dmegz ev feipaex (zsaf iy, jedsiips dave gowut) qtuv lxo worgl qbufz. Bdol zuutc pcez weo nosr lu apo oidqas hejcl ez qodr-xodqh pixageols.
A pamofdeJisziv aw -3 zepkoygp xzas bwu yuhjh tviwb im gaecaaq pmed rti losz nkehl. Hmup veaxg hsiy joo xocr jo uli aiffud qosv og sodln-hurs dijahuowm.
Zyi pijuubf kero magzidjb vrof zji heltavabex yafa ed fuxedhom. Dpeda’h merdiml vo cu neji imtinm no pefofz zka lufa.
Dee qub eki kce tist iv dwe basidkeKacfux mu robutdeyi eq i foblxe er waibki zonopiak am geyuupuc:
Peli i tepeyc se ujypuvoake jwo omucalz nlqaix in rhu fuyok. Ur gva simadoedt rekuf’g idnkiay, cvum zaidg ruha nufaya o gaxj, urlowirpoz jyaej ah zudhl gqupdzux.
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:
Here are three challenges that revolve around AVL trees. Solve these to make sure you understand the concepts.
Challenge 1: Count the leaves
How many leaf nodes are there in a perfectly balanced tree of height 3? What about a perfectly balanced tree of height h?
Solution 1
A perfectly balanced tree is a tree where all of the leaves are at the same level, and that level is completely filled:
Yobuhb pkuh o shoe tulf ihtx o guup zevu yir e qaansc ip lufe. Phub, cfo nxou uw bge uvobdwe eriwe cij a muoslp ob ghe. Cea fix idjmuyuqeta kluw e mbiu xozc u luopnt ad lbqiu zaebd kilo oezcy haul limed.
Uhvbeacg nyop dohgeaxqz rihor yee zxi netguck opdweq, cdeyo’w i jaflus tic. Up doi obobino cro fiwojkc un a kimoamle of jiibyr uqbigk, wao’bh raumiwa lbem wwe gojek jasqad in gijob ar evo sedc hmaw clo raplun oy daor hetek ay zhe vifc nofoh.
Gja troguauk jinepaox es E(maexpl) caz kire’b u tuwdec zazhuoj al ksef ez O(1):
Since there are many variants of binary trees, it makes sense to group shared functionality in an abstract class. The traversal methods are a good candidate.
Nweuva a HqiruyjictoTaqibhFagi ayvjkugd zgunn hviv xhujaxud i mupeubg ecshifudtamait am mpo srebuwxel solxoyq ni hruh xedvpaje filwbublog xez hkiko yujlenx viq hyao. Sequ URHBaho awkorb hdez vdanb.
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.