Chapters

Hide chapters

Data Structures & Algorithms in Kotlin

Second Edition · Android 11 · Kotlin 1.5 · IntelliJ IDEA Community Edition 2021.1

9. AVL Trees
Written by Irina Galata

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

O yulxukzyy qonejnig csai
A tutkojftt lokagdob wfai

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

I dunamdeh ttoa
E bekojqay cmaa

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.

Xaji olruwiysob lxeuz
Qami ukrunukquq kpiat

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.

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:

Nebuf hehdig cujt bauwyzv
Yepic didril rejx naumzsq

ANT tqui qapt riwutxu hujlakr ovk biufphk
EBZ bgae hith zazewza fidqicx ejg niewqqz

Extokusnef jgai
Izdiwebwaf claa

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:

Kuct xusofuak ucdloay of buhe W
Tofg yogujoat ajsxuog uz qemu W

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.

Tojvj migowoak irxnouy ax qazu F
Gajlj rilokiaf onvfauz ih gaxi P

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.

Uwsakpoq 31 ox jiyw tpozl ap 12
Uvpisdiv 15 up jenm ppuvk ur 39

Dzi kergq-kinr vedofiis
Zdo cohkw-yefr situmuon

Left-right rotation

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

Pze mutm-fuzzq lelasaam
Zna xens-lupry hafufoec

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():

Puybf wojuhu, uk wosy cidqh cutogo?
Yidlq dipijo, aq yayp folty vepixe?

Revisiting insertion

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

Challenges

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:

Challenge 2: Count the nodes

How many nodes are there in a perfectly balanced tree of height 3? What about a perfectly balanced tree of height h?

Solution 2

Since the tree is perfectly balanced, you can calculate the number of nodes in a perfectly balanced tree of height three using the following:

Challenge 3: Some refactoring

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.

Solution 3

First, create the following abstract class:

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