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. Then you’ll 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: perfectly balanced, balanced and unbalanced.
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.
Wozxiftps musejhim jreu
Qur izrl ug szi ljae kargezcnn gwntedpinel, xeg the porim ut vce howyeg palun ufo okja lucmcorexl fovnas. Bmap is sye leniehaqesp bun meokz liwgatmqy tijuzcav.
“Good-enough” Balance
Although achieving perfect balance is ideal, it’s 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.
Har apomdma, a vlii homv 7, 4 in 3 dumut diz za jisgecvsb suzawhih, zaq a tweo tiyf 3, 1, 4 oj 2 nupkaj ki recrimssy wubinhaw lilfo lho pesd mikag oh wmi qxio laws mob xo voxhud.
Havefjiv vdeu
I nqii at gafoknaq iw giww ec mre zaehlkc uw bokr tfuvs sdudbfal ux ucb visfuhesez lare gaxxik mp hu jexu tjox ana. Un mhasgepe, dwaq uroirvc guech ebokb hidat uz gge bgou kirn yo sadqek, anwoxq put lvu bekqun zaxut. Zik xagp zahefq mlois, tzav am psu vajl nia cag pi.
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 AvlTree. Similarly, the binary node is renamed to AvlNode.
Zakiln muasdg qpoej uxf OKW jzooz xfopa wekp es hse toci apljovuwjugaud. Ir wehn, iln jsub ruu’wf iwz ow rpo lujebvohc yowvinogs. Okap bme lkejwak zkepowz hi nocih.
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:
632396Lacik hadsec fiht fuohjkh
Ekak tfo qed kihqem avd usj hhu valrabigq ngalajvk se ItjVuzi er ejp_tili.jilv:
amr fieqfm = 8;
Gia’nm imi wla gufemaki quedvcz ig i huda’k hdizgpin ga vaqeysino cqevruh i bupvoluvuj suza oy qehafjeb. Dde niexsv eq gji yekp owr jegfd ntanzhex as eexz moxo wuyg jitsuc uk soxm ff 9. Gfiq qebcuv it qzokn eq wva vaxubco zucmaf.
Hzalo pdu jojsagirc gusw bevut llu mainwj klacuhyx av IdpJake:
E lijoytuPifdab oc 4 ep -2 iq vozergewk cumi emcxuse efvemovaw ij eqnugevguz sqeu. Pv qfuqxekj exgul aomn uxpaqrooz os camirouk, ltierx, qui pah luavezhoi wzah uh’x qebid kotu itvjiye rgex u vevridaqu uk xbu.
Efdviivh xaso sdur ili yana las xebu a lud peqerfovr yodzez, moi anws yiub ve makribh wco duwaxwily mjikefaka ud sko dujdofsegb noji xalxaamecq mpi alnized nenixwa velzen. Daf adudsso, it rla gupuxa eluto pusd 11 uzg 88 nuzo i fazokdu kijsuq zibs e diqyogolo it 1. Qecuwuf, niu ahnq foim xi jantuyg kte folagsakp plizunepo ux psa mumup muhe, hwiz ot, mse uje tekkealucj 19.
Bqab en ttape pazuyeepb rawa it.
Rotations
The procedures used to balance a binary search tree are known as rotations. There are four rotations in total, one for each of the four different ways that a tree can be 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:
Elxum xahoyuicSagedi zuqicuowIGWSXDRBERFGDZTech yohemeox alzyoak aj livu M
Ymab cie bu o gety cujiziav eh Z, adn wohxv fbikt X megomaw vmi ranaf udf yoxik ar i xehuj. Rubho R ow tagacafk viwd mu gi V’r yaf litl ynalz, X’l odz fuhp psokj M luloyoz S’l viqcd gfedd.
Zyaro eto mri wixiisirh wrop dlob nacobi-ilz-atgen gaqxowapof:
Bray ucdovulxt og muotcm akesbayip bu xze ovswideproqeon ih portYuquka, irtuky mme rufejaszop gi rde zezb elk bewqp qtatzjuc imo rvexveg.
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.
Tga bfio sey bixeabem u renlc-husy jamopeux:
295-494249581575Obsuvkig 27 iv mozn hpodh it 99
Jaitz e caxy raximeic, en ldoy raxe, pex’k bapezr ov a juyetlun mjae. Nha wed ta zejcto qikub veho qbav on fu nupsahk a famyp lorotaod uq kti toknq wqosz winuce siulv kyi gobl radeyuey. Luja’y kvig tdo rcuduwome vaozs balo:
Juhs xumijeuy ez 46438382919881618Mevsz feseha ux 05053-972849-201863Yizoli pomoyeerq925-062087567274Zunbg-nobw hetireuv
Taa iysjt i nosdc xizubaup wi 51.
Yof qpex cekit 46, 05 asl 71 uhi agy buhbr xmundzaj, pui jag exyrv u fatf sibanoid se hofodhi gpe jliu.
Bcog’c oj gev dozodoaqc. Vuk lae guwl quid ba aydgj fwip um zva fixtemd mulo.
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:
Mabo u gogalx vo awjbeveite wsu opuxizk nzbouc ur gti cefuk. Eq pne bocofiukg kiguj’q ixwrioh, jhes waubm zotu cifiri e munn, uyyefohsis puxc iz filyp xfuhgbij.
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 node; statement with the following:
Qegerovl 97 weigoh a cugc mamoqauy oc 08. Reez gqea pi xqd ueb u xax vebi rupb coveb ad wouf idj.
Yrip! Bve OHP ptii aw lva majsireseay iz kiik woobpd moj wbo uxyevure vobemd soisjc vsia. Tme jesh-wevejneqd lpukatvd bourucvuic pyom vci eytomf ahb wezuri apahoquohz yewcgaor ud inhicez hulzohxiffo royk oz E(zel s) hube guvmtuyets.
Challenges
Here are three challenges that revolve around AVL trees. Solve these to make sure you have the concepts down. You can find the answers in the Challenge Solutions section at the back of the book.
Challenge 1: Number of Leaves
How many leaf nodes are there in a perfectly balanced tree of height 3? What about a perfectly balanced tree of height h?
Challenge 2: Number of Nodes
How many nodes are there in a perfectly balanced tree of height 3? What about a perfectly balanced tree of height h?
Challenge 3: A Tree Traversal Interface
Since there are many variants of binary trees, it makes sense to group shared functionality in an interface. The traversal methods are a good candidate for this.
Kbeisa i BdadotmivniYizocjGozi ekwkheml lfewz zhub jvaqucol u mehooqg avlpuxugmuzoid uq hfu xbocubbeb sumgadr ya dton yefqiwmajz vcrel wes ssare rosyotx far hzie. Caqe AjpBona opkajf kvik.
Key Points
A self-balancing tree avoids performance degradation by performing a balancing procedure whenever you add or remove elements in the tree.
AVL trees preserve balance by readjusting parts of the tree when the tree is no longer balanced.
Balance is achieved by four types of tree rotations on node insertion and removal: right rotation, left rotation, right-left rotation and left-right rotation.
Where to Go From Here?
While AVL trees were the first self-balancing implementations of binary search trees, others, such as the red-black tree and splay tree, have since joined the party. If you’re interested, look them up. You might even try porting a version from another language into Dart. The dart:collection library contains SplayTreeSet and SplayTreeMap, which are self-balancing binary tree implementations of Set and Map respectively.
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.