Facebook Pixel
Step-by-Step Guide

How to Balance a Binary Search Tree (AVL Trees)

A step-by-step guide on how AVL Trees self-balance after every insertion and deletion using height tracking and rotations.

Understand the Balance Factor

An AVL Tree stays balanced by tracking the Balance Factor of every node. The Balance Factor is the height of the left subtree minus the height of the right subtree. If this value goes above positive one or below negative one at any node, the tree must be rebalanced.

Track the Height of Every Node

The height of a node is the length of the longest path from that node down to a leaf. A NULL node has a height of negative one and a leaf node has a height of zero. Update the height of a node every time its children change.

Identify the Four Imbalance Cases

There are four cases. Left Left means the imbalance is in the left subtree of the left child. Right Right means the imbalance is in the right subtree of the right child. Left Right means the imbalance is in the right subtree of the left child. Right Left means the imbalance is in the left subtree of the right child.

Fix Left Left with a Right Rotation

For the Left Left case, perform a single Right Rotation on the unbalanced node. The left child takes the place of the unbalanced node and the unbalanced node becomes the right child of the new root. The Binary Search Tree property is preserved throughout.

Fix Right Right with a Left Rotation

For the Right Right case, perform a single Left Rotation. The right child takes the place of the unbalanced node and the unbalanced node becomes the left child of the new root.

Fix Left Right and Right Left with Double Rotations

For the Left Right case, first perform a Left Rotation on the left child, then a Right Rotation on the unbalanced node. For the Right Left case, first perform a Right Rotation on the right child, then a Left Rotation on the unbalanced node.

Apply After Every Insert and Delete

After every insertion or deletion, walk back up from the affected node to the root. At each node, recalculate the height and balance factor. If any node is unbalanced, apply the correct rotation. This guarantees the tree always stays balanced and all operations remain logarithmic.

Ready to master this completely?

Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

Please Login.
Please Login.