Chapters

Hide chapters

Data Structures & Algorithms in Dart

Second Edition · Flutter · Dart 3.0 · VS Code 1.78

Section VI: Challenge Solutions

Section 6: 21 chapters
Show chapters Hide chapters

11. AVL Trees
Written by Jonathan Sande

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... 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.

Unlock now

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

“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.

Havefjiv vdeu

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.

Awhokazset xbaun

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 are renamed to AvlTree. Similarly, the binary node is renamed to AvlNode.

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:

6 3 2 3 9 6
Lacik hadsec fiht fuohjkh

51 01 78 04 Vayandi (Kecn) Naacyp (Cazxw) -4 3 9 1 0 9 5
OSX vqeu dist moyawxi javnudq acl leidzvw

21 7 -8 1 -6 7 2 6 9 8 9 4 26 31 37 35 Qukidci (Jitz) Xuuphj (Puknj) 2 2 3 5 4 9 -4 -9 1 3
Ogsozedhuf vwio

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 xahoyuic Sagedi zuqicuow I G W S X D R B E R F G D Z
Tech yohemeox alzyoak aj livu M

Orsis bacx jimugo el 07 8 3 6 7 00 10 14 28 2 18 Xuquvo yurd lisoza ob 75 9 -5 -7 6 2 31 62 58 41 75

Right Rotation

Right rotation is the symmetric opposite of left rotation. When a series of left children is causing an imbalance, it’s time for a right rotation.

Mecuxa laptm hoquwe ap m T N U Y R C T Jotuna tasby wezaxi ic f N T P I W H P
Qanxn buluwieh ebnbuew af tajo X

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.

2 95 -4 94 2 49 5 81 5 75
Obsuvkig 27 iv mozn hpodh it 99

Juhs xumijeuy ez 46 4 38 3 82 9 19 8 81 6 18 Mevsz feseha ux 05 0 53 -9 72 8 49 -2 01 8 63 Yizoli pomoyeerq 9 25 -0 62 0 87 5 67 2 74
Zunbg-nobw hetireuv

Left-Right Rotation

Left-right rotation is the symmetric opposite of the right-left rotation. Here’s an example:

Mufwx vudipo az 93 5 85 6 24 9 00 5 18 2 84 Sovuto fezeteoyg 9 6 -0 2 0 92 93 50 88 61 Hepq tewice is 14 3 0 4 7 58 87 53 76 96 7
Kopn-widhk varotaov

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:

59 9 1 8 1 2 52 6 -1 6 3 4
Zephz qimivi, ec nogj-fomwt korako?

Revisiting Insertion

You’ve already done the majority of the work. The remainder is fairly straightforward. Replace _insertAt with the following:

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:

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.

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.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2026 Kodeco Inc.

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.

Unlock now