Data Structures and Algorithms

AVL Trees

AVL trees are self-balancing, binary search trees. This means that the height of any two leaf nodes differs by at most one.

Functions

Same tree search function.

Sort is still an inorder traversal.

Now, insert is different. Here's the basic idea:

  • Insert like a BST
  • Rearrange tree to balance height

Each node has to record their height, and you can compute a node's balance factor:

If the absolute value of this balance factor is greater than one, then the node is out of balance.

These are rebalanced through rotations, basically interchanging the role of a parent and one of its children in a tree. This still must preserve the BST ordering among the keys in the nodes.

Right rotation: copy right right pointer of the left child to be the left pointer of the old parent.

Left rotation: Copy the left pointer of the right child to be the right pointer of the old parent.

Rotation is a local change only involving three pointers of two nodes.

Algorithm checkAndBal(Node *n)
    if bal(n) > +1
        if bal(n->left) < 0
            rotateLeft(n->left)
        rotateRight(n)
    else if bal(n) < -1
        if bal(n->right) > 0
            rotateRight(n->right)
        rotateLeft(n)