Open In App

How to insert Strings into an AVL Tree

AVL Tree is a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees cannot be more than one for all nodes.

Examples:



The above tree is AVL because the differences between the heights of the left and right subtrees for every node are less than or equal to 1. Below is the example that is not an AVL Tree:



The above tree is not AVL because the differences between the heights of the left and right subtrees for 8 and 12 are greater than 1. It can be defined as a type of binary search tree that has all its nodes with a balance factor of -1, 0, or 1.

What is the balance factor: It is the difference in height between the two subtrees. (Balance Factor: Height of Left subtree – Height of right subtree)

Insertion of Strings in AVL Tree:

Below example demonstration of inserting the days of the week in the order: {Tuesday, Monday, Thursday, Saturday, Sunday, Friday, Wednesday}

Approach:

Check if the tree is balanced:

This process should be repeated for the insertion of all of the remaining nodes.

Points to Remember:

Steps To Create AVL Tree:

Balance Factor = height of the left subtree – the height of right subtree = 1 – 0 = 1

Therefore, the tree is balanced. Monday is also balanced because of balance factor 0.

Note: In case if we don’t remember the rules of rotation of AVL tree, still it can be balanced we just need to remember that: Left node < Root < Right node.

Example:

   5                        4
  /                       /   \
 3     —–>      3       5
  \
   4

If the AVL tree is checked, now the entire AVL tree is height-balanced as all the nodes have balance factors -1, 0, 1.

Article Tags :