Author: Hayden Smith 2021
Why?
What?
AVL trees fix imbalances as soon as they occur. It aims to have the tree reasonably maintain balance with an O(log(n)) cost.
General Method:
Invented by Georgy Adelson-Velsky and Evgenii Landis (1962)
A tree is unbalanced (height) when:
This tree can be repaired by rotation:
This process would normally be O(n) as you have to traverse all nodes to figure out the height of any particular sub-tree.
However, we will store the balance data on each node (height or balance) which will make things faster, but also mean more to maintain.
Red numbers are height. Typically stored on node.
Green numbers are balance. Stored or calculated based on immediate children.
Rule: Rotate whenever tree |balance| > 1
Insertion of 6 will trigger a rotate right on 8.
Pseudocode
Pseudocode
insertAVL(tree, item):
if tree is empty:
return new node containing item
else if item = data(tree):
return tree
if item < data(tree):
left(tree) = insertAVL(left(tree),item)
else if item > data(tree):
right(tree) = insertAVL(right(tree),item)
LHeight = height(left(tree))
RHeight = height(right(tree))
if (LHeight - RHeight) > 1:
if item > data(left(tree)):
left(tree) = rotateLeft(left(tree))
tree = rotateRight(tree)
else if (RHeight - LHeight) > 1:
if item < data(right(tree)) then
right(tree) = rotateRight(right(tree))
tree=rotateLeft(tree)
return tree