0% found this document useful (0 votes)
12 views9 pages

AVL Tree

An AVL tree is a height-balanced binary search tree where the balance factor of each node is -1, 0, or +1, ensuring efficient operations. Key operations include search, insertion, and deletion, all of which maintain the balance through rotations (left, right, left-right, right-left) as necessary. The document also provides examples of AVL tree construction and code implementation for insertion and deletion operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views9 pages

AVL Tree

An AVL tree is a height-balanced binary search tree where the balance factor of each node is -1, 0, or +1, ensuring efficient operations. Key operations include search, insertion, and deletion, all of which maintain the balance through rotations (left, right, left-right, right-left) as necessary. The document also provides examples of AVL tree construction and code implementation for insertion and deletion operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

AVL Tree

AVL tree is a height-balanced binary search tree. That means, an AVL tree is also a binary
search tree but it is a balanced tree. A binary tree is said to be balanced if, the difference
between the heights of left and right subtrees of every node in the tree is either -1, 0 or +1. In
other words, a binary tree is said to be balanced if the height of left and right children of
every node differ by either -1, 0 or +1. In an AVL tree, every node maintains an extra
information known as balance factor. The AVL tree was introduced in the year 1962 by
G.M. Adelson-Velsky and E.M. Landis.

An AVL tree is a balanced binary search tree. In an AVL tree, balance factor of every
node is either -1, 0 or +1.
Balance factor of a node is the difference between the heights of the left and right subtrees of
that node. The balance factor of a node is calculated either height of left subtree - height of
right subtree (OR) height of right subtree - height of left subtree. In the following
explanation, we calculate as follows...
Balance factor = height Of Left Subtree – height of Right Subtree

AVL Rotation

 Left rotation
 Right rotation
 Left-Right rotation
 Right-Left rotation

Left Rotation: When we perform insertion at the left subtree, then it is a left rotation
Right Rotation: When we perform insertion at the right subtree, then it is a right rotation.

Left-Right Rotation

Right-Left Rotation

Left Right Rotation (LR Rotation)


The LR Rotation is a sequence of single left rotation followed by a single right rotation. In
LR Rotation, at first, every node moves one position to the left and one position to right from
the current position. To understand LR Rotation, let us consider the following insertion
operation in AVL Tree...
Right Left Rotation (RL Rotation)
The RL Rotation is sequence of single right rotation followed by single left rotation. In RL
Rotation, at first every node moves one position to right and one position to left from the
current position. To understand RL Rotation, let us consider the following insertion operation
in AVL Tree...

Operations on an AVL Tree


The following operations are performed on AVL tree...

1. Search
2. Insertion
3. Deletion

Search Operation in AVL Tree


In an AVL tree, the search operation is performed with O(log n) time complexity. The search
operation in the AVL tree is similar to the search operation in a Binary search tree. We use
the following steps to search an element in AVL tree...

 Step 1 - Read the search element from the user.

 Step 2 - Compare the search element with the value of root node in the tree.

 Step 3 - If both are matched, then display "Given node is found!!!" and terminate the
function

 Step 4 - If both are not matched, then check whether search element is smaller or
larger than that node value.

 Step 5 - If search element is smaller, then continue the search process in left subtree.
 Step 6 - If search element is larger, then continue the search process in right subtree.

 Step 7 - Repeat the same until we find the exact element or until the search element is
compared with the leaf node.

 Step 8 - If we reach to the node having the value equal to the search value, then
display "Element is found" and terminate the function.

 Step 9 - If we reach to the leaf node and if it is also not matched with the search
element, then display "Element is not found" and terminate the function.

Insertion Operation in AVL Tree


In an AVL tree, the insertion operation is performed with O(log n) time complexity. In AVL
Tree, a new node is always inserted as a leaf node. The insertion operation is performed as
follows...

 Step 1 - Insert the new element into the tree using Binary Search Tree insertion logic.

 Step 2 - After insertion, check the Balance Factor of every node.

 Step 3 - If the Balance Factor of every node is 0 or 1 or -1 then go for next


operation.

 Step 4 - If the Balance Factor of any node is other than 0 or 1 or -1 then that tree is
said to be imbalanced. In this case, perform suitable Rotation to make it balanced and
go for next operation.

Deletion Operation in AVL Tree


The deletion operation in AVL Tree is similar to deletion operation in BST. But after every
deletion operation, we need to check with the Balance Factor condition. If the tree is balanced
after deletion go for next operation otherwise perform suitable rotation to make the tree
Balanced. A node is always deleted as a leaf node. After deleting a node, the balance factors
of the nodes get changed. To rebalance the balance factor, suitable rotations are performed.
Algorithm for Deletion in an AVL Tree is as follows.
Step 1: START
Step 2: Find the node in the tree. If the element is not found, go to step 7.
Step 3: Delete the node using BST deletion logic.
Step 4: Calculate and check the balance factor of each node.
Step 5: If the balance factor follows the AVL criterion, go to step 7.
Step 6: Else, perform tree rotations to balance the unbalanced nodes. Once the tree is
balanced go to step 7.
Step 7: END

There are three cases for deleting a node:


1. If nodeToBeDeleted is the leaf node (ie. does not have any child), then
remove nodeToBeDeleted.
2. If nodeToBeDeleted has one child, then substitute the contents of nodeToBeDeleted with that
of the child. Remove the child.
3. If nodeToBeDeleted have two children, find the in-order
successor w of nodeToBeDeleted (ie. node with a minimum value of key in the right subtree).
Example: Construct an AVL tree by inserting the following elements in the given order.

63, 9, 19, 27, 18, 108, 99, 81


Example: Construct an AVL Tree by inserting numbers from 1 to 8.
import sys

# Create a tree node


class TreeNode(object):
def __init__(self, key):
self.key = key
self.left = None
self.right = None
self.height = 1

class AVLTree(object):

# Function to insert a node


def insert_node(self, root, key):

# Find the correct location and insert the node


if not root:
return TreeNode(key)
elif key < root.key:
root.left = self.insert_node(root.left, key)
else:
root.right = self.insert_node(root.right, key)

root.height = 1 + max(self.getHeight(root.left),
self.getHeight(root.right))

# Update the balance factor and balance the tree


balanceFactor = self.getBalance(root)
if balanceFactor > 1:
if key < root.left.key:
return self.rightRotate(root)
else:
root.left = self.leftRotate(root.left)
return self.rightRotate(root)

if balanceFactor < -1:


if key > root.right.key:
return self.leftRotate(root)
else:
root.right = self.rightRotate(root.right)
return self.leftRotate(root)

return root

# Function to delete a node


def delete_node(self, root, key):

# Find the node to be deleted and remove it


if not root:
return root
elif key < root.key:
root.left = self.delete_node(root.left, key)
elif key > root.key:
root.right = self.delete_node(root.right, key)
else:
if root.left is None:
temp = root.right
root = None
return temp
elif root.right is None:
temp = root.left
root = None
return temp
temp = self.getMinValueNode(root.right)
root.key = temp.key
root.right = self.delete_node(root.right,
temp.key)
if root is None:
return root

# Update the balance factor of nodes


root.height = 1 + max(self.getHeight(root.left),
self.getHeight(root.right))

balanceFactor = self.getBalance(root)

# Balance the tree


if balanceFactor > 1:
if self.getBalance(root.left) >= 0:
return self.rightRotate(root)
else:
root.left = self.leftRotate(root.left)
return self.rightRotate(root)
if balanceFactor < -1:
if self.getBalance(root.right) <= 0:
return self.leftRotate(root)
else:
root.right = self.rightRotate(root.right)
return self.leftRotate(root)
return root

# Function to perform left rotation


def leftRotate(self, z):
y = z.right
T2 = y.left
y.left = z
z.right = T2
z.height = 1 + max(self.getHeight(z.left),
self.getHeight(z.right))
y.height = 1 + max(self.getHeight(y.left),
self.getHeight(y.right))
return y

# Function to perform right rotation


def rightRotate(self, z):
y = z.left
T3 = y.right
y.right = z
z.left = T3
z.height = 1 + max(self.getHeight(z.left),
self.getHeight(z.right))
y.height = 1 + max(self.getHeight(y.left),
self.getHeight(y.right))
return y

# Get the height of the node


def getHeight(self, root):
if not root:
return 0
return root.height

# Get balance factore of the node


def getBalance(self, root):
if not root:
return 0
return self.getHeight(root.left) - self.getHeight(root.right)

def getMinValueNode(self, root):


if root is None or root.left is None:
return root
return self.getMinValueNode(root.left)

def preOrder(self, root):


if not root:
return
print("{0} ".format(root.key), end="")
self.preOrder(root.left)
self.preOrder(root.right)

# Print the tree


def printHelper(self, currPtr, indent, last):
if currPtr != None:
sys.stdout.write(indent)
if last:
sys.stdout.write("R----")
indent += " "
else:
sys.stdout.write("L----")
indent += "| "
print(currPtr.key)
self.printHelper(currPtr.left, indent, False)
self.printHelper(currPtr.right, indent, True)

myTree = AVLTree()
root = None
nums = [22, 14, 72, 44, 25, 63, 98]
for num in nums:
root = myTree.insert_node(root, num)
myTree.printHelper(root, "", True)

key = 25
root = myTree.delete_node(root, key)
print("After Deletion: ")
myTree.printHelper(root, "", True)

You might also like