# AVL Tree

#### In this tutorial, you will learn what an avl tree is. Also, you will find working examples of various operations performed on an avl tree in C.

AVL tree is a self-balancing binary search tree in which each node maintains extra information called a balance factor whose value is either -1, 0 or +1.

AVL tree got its name after its inventor Georgy Adelson-Velsky and Landis.

## Balance Factor

Balance factor of a node in an AVL tree is the difference between the height of the left subtree and that of the right subtree of that node.

Balance Factor = (Height of Left Subtree – Height of Right Subtree) or (Height of Right Subtree – Height of Left Subtree)

The self balancing property of an avl tree is maintained by the balance factor. The value of balance factor should always be -1, 0 or +1.

An example of a balanced avl tree is:

## Operations on an AVL tree

Various operations that can be performed on an AVL tree are:

## Rotating the subtrees in an AVL Tree

In rotation operation, the positions of the nodes of a subtree are interchanged.

There are two types of rotations:

### Left Rotate

In left-rotation, the arrangement of the nodes on the right is transformed into the arrangements on the left node.

Algorithm

- Let the initial tree be:

- If
`y`has a left subtree, assign`x`as the parent of the left subtree of`y`.

- If the parent of
`x`is`NULL`

, make`y`as the root of the tree. - Else if
`x`is the left child of`p`, make`y`as the left child of`p`. - Else assign
`y`as the right child of`p`.

- Make
`y`as the parent of`x`.

### Right Rotate

In left-rotation, the arrangement of the nodes on the left is transformed into the arrangements on the right node.

- Let the initial tree be:

- If
`x`has a right subtree, assign y as the parent of the right subtree of`x`.

- If the parent of
`y`is`NULL`

, make`x`as the root of the tree. - Else if
`y`is the right child of its parent`p`, make`x`as the right child of`p`. - Else assign
`x`as the left child of`p`.

- Make
`x`as the parent of`y`.

### Left-Right and Right-Left Rotate

In left-right rotation, the arrangements are first shifted to the left and then to the right.

- Do left rotation on x-y.

- Do right rotation on y-z.

In right-left rotation, the arrangements are first shifted to the right and then to the left.

- Do right rotation on x-y.

- Do left rotation on z-y.

## Algorithm to insert a newNode

A `newNode` is always inserted as a leaf node with balance factor equal to 0.

- Let the initial tree be:

Let the node to be inserted be:

- Go to the appropriate leaf node to insert a
`newNode`using the following recursive steps. Compare`newKey`with`rootKey`of the current tree.- If
`newKey`<`rootKey`, call insertion algorithm on the left subtree of the current node until the leaf node is reached. - Else if
`newKey`>`rootKey`, call insertion algorithm on the right subtree of current node until the leaf node is reached. - Else, return
`leafNode`.

- If
- Compare
`leafKey`obtained from the above steps with`newKey`:- If
`newKey`<`leafKey`, make newNode as the`leftChild`of`leafNode`. - Else, make
`newNode`as rightChild of`leafNode`.

- If
- Update
`balanceFactor`of the nodes.

- If the nodes are unbalanced, then rebalance the node.
- If
`balanceFactor`> 1, it means the height of the left subtree is greater than that of the right subtree. So, do a right rotation or left-right rotation- If
`newNodeKey`<`leftChildKey`do right rotation. - Else, do left-right rotation.

- If
- If
`balanceFactor`< -1, it means the height of the right subtree is greater than that of the left subtree. So, do right rotation or right-left rotation- If
`newNodeKey`>`rightChildKey`do left rotation. - Else, do right-left rotation

- If

- If
- The final tree is:

## Algorithm to Delete a node

A node is always deleted as a leaf node. After deleting a node, the balance factors of the nodes get changed. In order to rebalance the balance factor, suitable rotations are performed.

- Locate
`nodeToBeDeleted`(recursion is used to find`nodeToBeDeleted`in the code used below).

- There are three cases for deleting a node:
- If
`nodeToBeDeleted`is the leaf node (ie. does not have any child), then remove`nodeToBeDeleted`. - If
`nodeToBeDeleted`has one child, then substitute the contents of`nodeToBeDeleted`with that of the child. Remove the child. - If
`nodeToBeDeleted`has two children, find the inorder successor`w`of`nodeToBeDeleted`(ie. node with a minimum value of key in the right subtree).

- Substitute the contents of
`nodeToBeDeleted`with that of`w`.

- Remove the leaf node
`w`.

- Substitute the contents of

- If
- Update
`balanceFactor`of the nodes.

- Rebalance the tree if the balance factor of any of the nodes is not equal to -1, 0 or 1.
- If
`balanceFactor`of`currentNode`> 1,- If
`balanceFactor`of`leftChild`>= 0, do right rotation.

- Else do left-right rotation.

- If
- If
`balanceFactor`of`currentNode`< -1,- If
`balanceFactor`of`rightChild`<= 0, do left rotation. - Else do right-left rotation.

- If

- If
- The final tree is:

## C Examples

```
// AVL tree implementation in C
#include <stdio.h>
#include <stdlib.h>
// Create Node
struct Node {
int key;
struct Node *left;
struct Node *right;
int height;
};
int max(int a, int b);
// Calculate height
int height(struct Node *N){
if (N == NULL)
return 0;
return N->height;
}
int max(int a, int b){
return (a > b) ? a : b;
}
// Create a node
struct Node *newNode(int key){
struct Node *node = (struct Node *)
malloc(sizeof(struct Node));
node->key = key;
node->left = NULL;
node->right = NULL;
node->height = 1;
return (node);
}
// Right rotate
struct Node *rightRotate(struct Node *y){
struct Node *x = y->left;
struct Node *T2 = x->right;
x->right = y;
y->left = T2;
y->height = max(height(y->left), height(y->right)) + 1;
x->height = max(height(x->left), height(x->right)) + 1;
return x;
}
// Left rotate
struct Node *leftRotate(struct Node *x){
struct Node *y = x->right;
struct Node *T2 = y->left;
y->left = x;
x->right = T2;
x->height = max(height(x->left), height(x->right)) + 1;
y->height = max(height(y->left), height(y->right)) + 1;
return y;
}
// Get the balance factor
int getBalance(struct Node *N){
if (N == NULL)
return 0;
return height(N->left) - height(N->right);
}
// Insert node
struct Node *insertNode(struct Node *node, int key){
// Find the correct position to insertNode the node and insertNode it
if (node == NULL)
return (newNode(key));
if (key < node->key)
node->left = insertNode(node->left, key);
else if (key > node->key)
node->right = insertNode(node->right, key);
else
return node;
// Update the balance factor of each node and
// Balance the tree
node->height = 1 + max(height(node->left),
height(node->right));
int balance = getBalance(node);
if (balance > 1 && key < node->left->key)
return rightRotate(node);
if (balance < -1 && key > node->right->key)
return leftRotate(node);
if (balance > 1 && key > node->left->key) {
node->left = leftRotate(node->left);
return rightRotate(node);
}
if (balance < -1 && key < node->right->key) {
node->right = rightRotate(node->right);
return leftRotate(node);
}
return node;
}
struct Node *minValueNode(struct Node *node){
struct Node *current = node;
while (current->left != NULL)
current = current->left;
return current;
}
// Delete a nodes
struct Node *deleteNode(struct Node *root, int key){
// Find the node and delete it
if (root == NULL)
return root;
if (key < root->key)
root->left = deleteNode(root->left, key);
else if (key > root->key)
root->right = deleteNode(root->right, key);
else {
if ((root->left == NULL) || (root->right == NULL)) {
struct Node *temp = root->left ? root->left : root->right;
if (temp == NULL) {
temp = root;
root = NULL;
} else
*root = *temp;
free(temp);
} else {
struct Node *temp = minValueNode(root->right);
root->key = temp->key;
root->right = deleteNode(root->right, temp->key);
}
}
if (root == NULL)
return root;
// Update the balance factor of each node and
// balance the tree
root->height = 1 + max(height(root->left),
height(root->right));
int balance = getBalance(root);
if (balance > 1 && getBalance(root->left) >= 0)
return rightRotate(root);
if (balance > 1 && getBalance(root->left) < 0) {
root->left = leftRotate(root->left);
return rightRotate(root);
}
if (balance < -1 && getBalance(root->right) <= 0)
return leftRotate(root);
if (balance < -1 && getBalance(root->right) > 0) {
root->right = rightRotate(root->right);
return leftRotate(root);
}
return root;
}
// Print the tree
void printPreOrder(struct Node *root){
if (root != NULL) {
printf("%d ", root->key);
printPreOrder(root->left);
printPreOrder(root->right);
}
}
int main(){
struct Node *root = NULL;
root = insertNode(root, 2);
root = insertNode(root, 1);
root = insertNode(root, 7);
root = insertNode(root, 4);
root = insertNode(root, 5);
root = insertNode(root, 3);
root = insertNode(root, 8);
printPreOrder(root);
root = deleteNode(root, 3);
printf("nAfter deletion: ");
printPreOrder(root);
return 0;
}
```

## Complexities of Different Operations on an AVL Tree

Insertion |
Deletion |
Search |

O(log n) | O(log n) | O(log n) |

## AVL Tree Applications

- For indexing large records in databases
- For searching in large databases

# Python Example for Beginners

## Two Machine Learning Fields

There are two sides to machine learning:

**Practical Machine Learning:**This is about querying databases, cleaning data, writing scripts to transform data and gluing algorithm and libraries together and writing custom code to squeeze reliable answers from data to satisfy difficult and ill defined questions. It’s the mess of reality.**Theoretical Machine Learning**: This is about math and abstraction and idealized scenarios and limits and beauty and informing what is possible. It is a whole lot neater and cleaner and removed from the mess of reality.

**Data Science Resources: Data Science Recipes and Applied Machine Learning Recipes**

**Introduction to Applied Machine Learning & Data Science for Beginners, Business Analysts, Students, Researchers and Freelancers with Python & R Codes @ Western Australian Center for Applied Machine Learning & Data Science (WACAMLDS) !!!**

Latest end-to-end Learn by Coding Recipes in Project-Based Learning:

**Applied Statistics with R for Beginners and Business Professionals**

**Data Science and Machine Learning Projects in Python: Tabular Data Analytics**

**Data Science and Machine Learning Projects in R: Tabular Data Analytics**

**Python Machine Learning & Data Science Recipes: Learn by Coding**

**R Machine Learning & Data Science Recipes: Learn by Coding**

**Comparing Different Machine Learning Algorithms in Python for Classification (FREE)**

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause.The information presented here could also be found in public knowledge domains.