Avl Tree and Its Applications
Avl Tree and Its Applications
.
Why AVL Tree?
- An AVL tree is a self-balancing BST that ensures
the height of the tree remains relatively small by
rotating nodes when the balance factor becomes
too large.
We perform
rotation in AVL
tree only in
case if Balance 4. Left-Right Rotation:
A left-right rotation is a combination in which first left rotation
Factor is other takes place after that right rotation executes.
than -1, 0,
and 1.
Node leftRotate(Node x) { //x=10
Node y = x.right; // y is the right child of x
L Rotation //y=20
Algorithm Node z = y.left; // z is the left child of y //z=30
Tree }
// Get height of a node
Balancing, int height(Node N) {
Height, }
return (N == null) ? 0 : N.height;
Finding // Get the node with the smallest key in the tree
Minimum Node minValueNode(Node node) {
return node;
}
if (key < node.key) {
}
return search(node.right, key);
}
Deletion Node delete(Node root, int key) {
if (root == null)
Algorithm return root;
10 if (key < root.key)
root.left = delete(root.left, key);
else if (key > root.key)
5 20 root.right = delete(root.right, key);
else {
if ((root.left == null) || (root.right == null)) {
Node temp = (root.left != null) ? root.left : root.right;
2 9 30 if (temp == null) {
root = null;
} else {
7 root = temp;
}
} else {
Node temp = minValueNode(root.right);
root.key = temp.key;
root.right = delete(root.right, temp.key);
}
if(root==null)
return root;
root.height=Math.max(height(root.left), height(root.right))+1;
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){
root.right=rightRotate(root.right);
return leftRotate(root);
}
return root;
}
APPLICATIONS
•Databases: AVL trees are widely used in database systems for maintaining balanced search trees. They ensure
efficient operations like insertion, deletion, and searching with a time complexity of O(logn),O(\log n) and
O(logn), which is crucial for indexing large datasets.
•Memory Management: AVL trees help allocate and free memory blocks efficiently in dynamic memory
systems. By keeping memory allocations balanced, they reduce fragmentation and speed up memory access
operations.
•Network Routing: AVL trees are utilized in routing tables for storing and efficiently retrieving routes. Their
self-balancing nature ensures quick access and updates, crucial for managing network paths dynamically.
•File Systems: File directories often rely on AVL trees to manage hierarchical data structures. This ensures quick
lookups, additions, and deletions, maintaining system performance as files are frequently accessed or modified.
•Gaming: AVL trees handle dynamic data in games, such as managing player rankings or high scores. Their
balanced structure ensures that retrieving or updating scores happens in minimal time, enhancing the gaming
experience.