blog/algorithms/08-rb-trees/2024-01-22-avl.md
Matej Focko f46561653f
algorithms(avl): add WIP
Signed-off-by: Matej Focko <me@mfocko.xyz>
2024-02-04 13:58:41 +01:00

2 KiB

id title description tags last_update
avl AVL tree Looking at a tree that's very similar to the red-black tree.
AVL tree
balanced trees
zig
date
2024-01-22

Introduction

AVL tree is the first self-balanced tree to be ever invented. However if we look at the commonly used data structures to represent the set or a map, we will find out that red-black trees (or even its relaxation LLRB1) or hash tables are the most used.

Let's look into the AVL tree and how it is related to its “successor” red-black tree, they are closer than you can imagine.

Properties

AVL tree is height-balanced same as the red-black tree. The key difference lies in the invariants that need to be satisfied. In this case we require that subtrees of any node differ in their heights at most by 1. If we were to write it as a condition for node n, we can write it like:

$$ \vert Height(Right(n)) - Height(Left(n)) \vert \leq 1

Because the only allowed values here are \left\{ -1, 0, 1 \right\}, it is possible to simplify the structure of the nodes in memory by using a one byte of memory to store the “state” of the subtrees in a node.

:::tip

Some representations use a sign notation of +, 0 and - which represent where is the tree leaning to:

  • - means the left subtree has bigger height ⇒ tree is leaning to left
  • 0 means both subtrees have the same height ⇒ they're equal
  • + means the right subtree has bigger height ⇒ tree is leaning to right

:::

It is also possible to find representations that allow leaning only to one side, by enforcing this requirement you can use just boolean to represent the state, i.e. the tree is leaning to one side, or is not.

Implementation

Let's have a look at the implementation of the AVL tree in some language.

Insertion

Deletion

Comparison with the red-black tree

Bonus: Implementation of the BST in Java