AVL Tree Data Structure

Binary Search Tree(BST) is a binary tree where each node has the following properties:

  • The node’s left subtree contains keys smaller than or equal to the node’s key.
  • The node’s right subtree contains keys greater than or equal to the node’s key.
  • The left and right subtrees are valid binary search trees.

Following are some examples of binary search trees:

examples of binary search trees

Why binary search tree?

The primary use of binary search trees is for searching. Searching for a given value in a binary search tree is easy because elements in BST are stored in a sorted order. Steps for searching in a BST:

  • Compare the element with the root of the tree. If the value is the same, return the node. Otherwise, if the element is less than the root’s value, move to the left subtree. If it is greater, move to the right subtree.
  • Repeat this process recursively or iteratively until we found the element.
  • If we reach a null node without finding the element, return false.

Time complexity of searching in a BST depends on its height. The worst-case time complexity of searching is O(n). This is the scenario of a skewed tree where each level has only one node and the height of the tree is n (n is the number of nodes in the BST). The best-case time complexity of searching is O(logn), as the minimum height achieved for a binary tree with n nodes is logn. Such a BST is a balanced binary search tree.

Why is there a difference in the search times in the two BSTs, even though they have the same set of nodes? Because their structure is different. Even though two BSTs have the same set of nodes, their structure depends on the insertion order of the nodes. This is the drawback of BSTs. So the time required for searching for a given element varies from O(logn) to O(n). Can we improve this?

Introduction to AVL Tree Data structure 

AVL Trees, named after its inventors Adelson-Velsky and Landis, is a unique variation of the Binary Search Tree, which is a self-balancing BST. The property of AVL Trees is that they automatically attain the tree's minimum possible height after executing any operation.

We have the following three elements,{10, 20, 30}, and we want to insert them into a BST. There are 6 ways of inserting the values into the BST. The following image shows the different orders and the resulting BSTs.

All possible bst of 3 nodes

Two orders result in a BST of height 1, whereas the remaining four result in height 2. Try to think if there is any way of converting the height 2 BSTs into height 1 BSTs. We can do some rotations while maintaining the BST property to convert the BSTs of height 2 into a BST of height 1.

Balance Factor

We define a term balance factor for each node. The balance factor for a node is the difference between the height of its left subtree and right subtree. Balance factor = abs(right subtree height - left subtree height).

In an AVL tree, all nodes should have a balance factor in {0, 1}. The following image shows the balance factor for each node for all BSTs from the first image. The value in red is the balance factor of each node.

Balance factor in AVL tree

We can also follow the other convention, where we just take the difference between the height of left and right subtree. Here negative balance factor means right imbalance, positive balance factor means left imbalance.

getBalanceFactor(node)
    if node is null
        return 0
    // Balance factor = height of left subtree - height of right subtree
    return getHeight(node.left) - getHeight(node.right)

All Types of Possible Rotations

As we had seen earlier, if a BST is not balanced, rotations are required to convert that tree to a balanced BST. Let's study each type of rotation in detail.

LL Rotation
Consider the following insertion order:

LL Rotation in AVL tree

Initially, the tree is balanced. Inserting 10 into the left subtree of the root’s left child makes the tree too heavy on the left. This is called a left-left (LL) imbalance. To restore balance, we perform a right rotation at the root. The rotation moves the left child up and the root down to its right, which redistributes the nodes while preserving their order in the binary search tree. This is similar to shifting weight around a pivot to bring both sides back into balance.

LL_rotation(node)
    child = node.left
    // Move child's right subtree to become node's left subtree.
    node.left = child.right
    // Make node the right child of child.
    child.right = node
    // Update the heights after the rotation.
    node.height = max(height(node.left), height(node.right)) + 1
    child.height = max(height(child.left), height(child.right)) + 1

    return child

RR Rotation
This case is the mirror image of a left-left imbalance. The tree becomes unbalanced when a new node is inserted into the right subtree of the right child of the unbalanced node. This is called a right-right (RR) imbalance. Consider the following insertion order to understand this scenario:

RR Rotation in AVL tree

RR_rotation(node)
    child = node.right
    // Move child's left subtree to become node's right subtree.
    node.right = child.left
    // Make node the left child of child.
    child.left = node
    // Update heights after the rotation.
    node.height = max(height(node.left), height(node.right)) + 1
    child.height = max(height(child.left), height(child.right)) + 1

    return child

LR Rotation

So far, we have looked at single-direction imbalances: left-left (LL) and right-right (RR). In this scenario, the imbalance is in the right subtree of the left child, so it is called a left-right (LR) imbalance.

It is impossible to balance the tree with a single rotation while preserving the binary search tree order. Instead, we need two rotations: first, a left rotation on the left child, then a right rotation on the unbalanced node.

Consider the following insertion order:

AVL tree LR rotation example

LR_rotation(node)
    // First, rotate left at the left child.
    node.left = RR_rotation(node.left)
    // Then, rotate right at the imbalanced node.
    return LL_rotation(node)

As we can see, after applying a left rotation on the left node of the root node, we get a left-of-left imbalance. We have seen how to handle this case: we perform a right rotation on the root. Now tree becomes balanced. Steps of LR rotation:

  1. Perform a left rotation on the left subtree of the imbalanced node as the left child has a right imbalance. This process turns the imbalance from right-of-left to left-of-left.
  2. Perform a right rotation on the imbalanced node.

RL Rotation
An RL (right-left) imbalance is a scenario in which a node becomes too heavy on the right, and its right child becomes too heavy on the left. This can happen when a new node is inserted into the left subtree of the imbalanced node’s right child. We can correct it with a right rotation on the right child, followed by a left rotation on the imbalanced node.

Consider the following insertion order to understand this scenario:

RL Rotation in AVL tree

RL_rotation(node)
    // First, rotate right at the right child.
    node.right = LL_rotation(node.right)
    // Then, rotate left at the imbalanced node.
    return RR_rotation(node)

As we have seen, rotations restore balance by restructuring a small part of the tree involving three nodes: the unbalanced node, its child, and its grandchild.

Here is an interesting case! After an insertion or deletion, the change can affect the balance factors of the node’s ancestors. To restore balance, we start at the changed node and move upward toward the root, updating heights and checking balance factors. When we find an imbalanced ancestor, we apply the appropriate rotation and reconnect the rotated subtree to its parent. We continue checking the ancestors until we reach the root. This bottom-up process ensures that the entire AVL tree is balanced after the operation.

Operations on the AVL Tree

Insertion in AVL tree

To insert a value into a BST, start at the root and compare the value with each node:

  1. If the new value is smaller than the current node’s value, move to the left child.
  2. If the new value is larger, move to the right child.
  3. If the values are equal, stop because this BST stores only unique values.
  4. Continue until you reach an empty child position, then insert the new node there.

So, a new node is inserted as a leaf in the BST, so its balance factor is always 0. Inserting it may change the balance factors of other nodes in the tree, so we need to check whether the tree is still balanced. We only need to check the balance factors of the new node’s ancestors. Think about why we don’t need to check the balance factors of the tree’s other nodes.

When we insert a new node into a tree, only the heights of its ancestors may change, which can affect their balance factors. So, we traverse from the parent of the inserted node toward the root, fixing any imbalances we encounter. This process of checking the ancestors of the newly inserted node for imbalances is called retracing. If the tree becomes unbalanced after an insertion, retracing helps us identify the nodes where rotations are needed to rebalance it.

Insertion in AVL tree example

Let's summarise the steps for inserting a node in an AVL tree.

  1. Insert the node in the tree using BST insertion logic.
  2. Calculate and check the balance factor of the ancestor of the inserted node.
  3. Perform tree rotations if required according to the type of imbalance.
  4. Retrace till the root node.

AVL tree insertion pseudocode

insert(node, val)
    if node is null
        // Insert val as a leaf node.
        create a new node
        node.data = val
        node.left = null
        node.right = null
        node.height = 0
        return node

    // Insert val according to the BST ordering.
    if node.data < val
        node.right = insert(node.right, val)
    else
        node.left = insert(node.left, val)

    // Update the node height and balance factor.
    node.height = max(height(node.left), height(node.right)) + 1
    balanceFactor = getBalanceFactor(node)

    // Handle a left-heavy subtree.
    if balanceFactor > 1
        if getBalanceFactor(node.left) equals 1
            // Left-left case
            node = LL_rotation(node)
        else
            // Left-right case
            node.left = RR_rotation(node.left)
            node = LL_rotation(node)

    // Handle a right-heavy subtree.
    else if balanceFactor < -1
        if getBalanceFactor(node.right) equals -1
            // Right-right case.
            node = RR_rotation(node)
        else
            // Right-left case.
            node.right = LL_rotation(node.right)
            node = RR_rotation(node)

    return node

Time complexity analysis of insertion in AVL Trees

There are three main steps in insertion: searching where the node will be inserted, inserting the node, and retracing while removing the imbalances.

  • Because an AVL tree is balanced, finding the position to insert a node using the BST property takes O(log n) time. This is a substantial improvement over the worst-case search time for insertion in an ordinary BST, which is O(n). Inserting the node at a leaf takes O(1) time.
  • Retracing takes O(log n) time. At most one node at each level needs to be rebalanced, and each rotation takes O(1) time. So the overall time complexity of inserting a node into an AVL tree is O(log n).

Deletion in AVL tree

Let's briefly recap deletion in BSTs. We traverse the tree from the root using the BST logic to search for the node in a BST. If we reach the end (NULL), the node to be deleted is not present in the tree.

Now, suppose the element is found in the tree. There are three different cases in which the deletion operation can be done depending upon the number of children of the node:

  • Case 1: When the node to be deleted is a leaf node: Then the node can be deleted directly as it does not have any children, i.e. it is a leaf node.
  • Case 2: When the node to be deleted has one subtree. So node to be deleted is replaced by its only child.
  • Case 3: When the node to be deleted has both the subtrees: This is a tricky case, as we need to decide with which node the node to be deleted has to be replaced. We can choose either a node from the left or right subtree.

If we choose a node from the left subtree, it should have the largest value in that subtree to preserve the BST property when replacing the node to be deleted. If we choose a node from the right subtree, it should have the smallest value in that subtree for the same reason.

Deletion in an AVL tree is similar to deletion in a BST and depends on the number of children of the node being deleted. But after deleting a node from an AVL tree, we must also check that the tree remains balanced. We do this by rebalancing the nodes during the retracing process, as discussed for insertion.

Deletion in AVL tree example

Let's summarise the steps for deleting a node in an AVL tree.

  1. Search node in the tree by the BST logic. If the element is not present, return.
  2. Delete the node.
  3. While retracing, calculate and check the balance factor of each ancestor node.
  4. Remove the imbalance using rotations.
  5. Repeat from step 3 till the root of the tree.

AVL tree deletion pseudocode

deleteNode(node, val)
    if node is null
        return null

    // Find the node to delete.
    if val < node.data
        node.left = deleteNode(node.left, val)
    else if val > node.data
        node.right = deleteNode(node.right, val)
    else
        // Node has no left child.
        if node.left is null
            temp = node.right
            free node
            return temp

        // Node has no right child.
        if node.right is null
            temp = node.left
            free node
            return temp

        // Node has two children: replace it with its inorder successor.
        temp = minimumNode(node.right)
        node.data = temp.data
        node.right = deleteNode(node.right, temp.data)

    // The subtree may now be empty.
    if node is null
        return null

    // Update height and check balance.
    node.height = max(height(node.left), height(node.right)) + 1
    balanceFactor = getBalanceFactor(node)

    // Rebalance a left-heavy node.
    if balanceFactor > 1
        if getBalanceFactor(node.left) >= 0
            node = LL_rotation(node)
        else
            node.left = RR_rotation(node.left)
            node = LL_rotation(node)

    // Rebalance a right-heavy node.
    else if balanceFactor < -1
        if getBalanceFactor(node.right) <= 0
            node = RR_rotation(node)
        else
            node.right = LL_rotation(node.right)
            node = RR_rotation(node)

    return node

Time complexity analysis of deletion in AVL Trees

Similar to insertion, there are three main steps: searching for the node to be deleted, deleting the node, and retracing while removing the imbalances.

  • Because an AVL tree is balanced, searching for a node using the BST property takes O(log n) time. In the worst case, deleting a node also takes O(log n) time. If the node has two children, we may need to find the leftmost node in its right subtree or the rightmost node in its left subtree.
  • Retracing takes O(log n) time. At most one node at each level needs to be rebalanced, and each rotation takes O(1) time. So the overall time complexity of deleting a node from an AVL tree is O(log n).

Conclusion

AVL Tree improves the performance of BST in the worst case by maintaining its height to logn by performing tree rotations according to the balance factor of each node.

Binary search tree vs AVL tree comparison

Enjoy learning, Enjoy algorithms!

More from EnjoyAlgorithms

Self-paced Courses and Blogs