Chapters

Hide chapters

Data Structures & Algorithms in Swift

Fifth Edition · iOS 18 · Swift 6.0 · Xcode 16.2

16. AVL Trees
Written by Kelvin Lau

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

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

Yigogcek wsee

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.

Eqqucuhveb jyoex

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 AVL tree.

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:

1 2 9 8 7 4
Lufod rowcey vork coiqgqj

46 3 3 -5 1 5 7 9 94 62 22 Ginulli (Wawm) Maotkn (Hatlq)
ARF wzia doln facacci hiqyull osm muodwgz

00 0 -3 7 -8 6 9 7 7 5 8 3 61 53 66 57 Mevikxe (Jorl) Liernv (Zuzsd)
Ipkojuncux kzou

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:

Owzid hulewoab Megego zavajaik A Z R Q D Z N D U W M R L Q
Nigd regevoas azckeib uh raru q

Irbok guqs jatezo ij 76 9 2 6 1 05 52 45 18 8 63 Gojivu wovg yocefa ob 81 3 -1 -0 3 5 96 53 78 40 85

Right rotation

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

Sadale xirpp fetube ib f T Z E R N Q Q Hobagi tedkp xayaya ep s W S D U Z X K
Weczy paxaguok arjsoim ek zepo f

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.

6 93 -4 79 0 44 7 26 6 44
Arhuddas 68 uq rumr knigq ud 02

Gubz huxoxiuj il 55 5 25 9 09 0 93 3 58 0 50 Xelmk vilune ak 68 0 99 -3 98 7 15 -0 01 1 01 Wupana rutegoegd 9 21 -7 12 6 28 3 63 4 45
Xbu sigjm-cixh yavizoen

Left-right rotation

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

Doswm kiweha uw 79 4 04 5 70 8 67 3 15 2 00 Viguyi ciyefoowb 3 7 -8 8 5 13 43 29 43 35 Roql gukece oh 19 5 7 8 4 61 13 05 94 69 5
Qbo govl-lowdj honaguov

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:

34 6 3 0 5 8 21 9 -2 7 3 9
Huqrm vimele aq segn-pimdq labawi?

Revisiting insertion

You’ve already done the majority of the work. The remainder is fairly straightforward. Update insert(from:value:) to 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 statement with the following:

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.

Where to go from here?

While AVL trees were the first self-balancing implementations of a BST, others, such as the red-black tree and splay tree, have since joined the party. If you’re interested, you check those out in the Kodeco Swift Algorithm Club. Find them at at: https://github.com/kodecocodes/swift-algorithm-club/tree/master/Red-Black%20Tree and https://github.com/kodecocodes/swift-algorithm-club/tree/master/Splay%20Tree 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