0% found this document useful (0 votes)
233 views6 pages

AVL Tree Implementation and Operations

An AVL tree is a self-balancing binary search tree where the heights of the left and right subtrees differ by at most one. It performs rebalancing operations like rotations after insertions or deletions to maintain this balance property. There are four types of rotations - right, left, left-right, and right-left - to rebalance the tree as needed. The AVL tree implementation uses a height attribute for each node and compares heights to determine if rebalancing is required.

Uploaded by

sathwik vagu
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)
233 views6 pages

AVL Tree Implementation and Operations

An AVL tree is a self-balancing binary search tree where the heights of the left and right subtrees differ by at most one. It performs rebalancing operations like rotations after insertions or deletions to maintain this balance property. There are four types of rotations - right, left, left-right, and right-left - to rebalance the tree as needed. The AVL tree implementation uses a height attribute for each node and compares heights to determine if rebalancing is required.

Uploaded by

sathwik vagu
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
  • AVL Tree Overview
  • Rotations
  • AVL Tree Implementation

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. 
A self-balancing tree is a binary search tree that balances the height after insertion and
deletion according to some balancing rules.
The balance factor of node N is height(right(N)) – height(left(N)). In an AVL Tree, the balance
factor of a node could be only one of 1, 0, or -1 values.
The AVL Tree checks the balance factor of its nodes after the insertion or deletion of a node. If
the balance factor of a node is greater than one or less than -1, the tree rebalances itself.
There are four operations to rebalance a tree:

 right rotation and


 left rotation.
 Left-Right Rotation.
 Right-Left Rotation

Right Rotation

Left Rotation 
Left-Right Rotation

Right-Left Rotation

Implementation:
class AVLNode
{

AVLNode left, right;


int data;
int height;

public AVLNode()
{
left = null;
right = null;
data = 0;
height = 0;
}

public AVLNode(int n)
{
left = null;
right = null;
data = n;
height = 0;
}
}

// AVL Tree Class

class AVLTree
{
private AVLNode root;
public AVLTree()
{
root = null;
}

private int height(AVLNode avlNode)


{
return avlNode == null ? -1 : [Link];
}

private int max(int lHeight, int rHeight)


{
return lHeight > rHeight ? lHeight : rHeight;
}

public void insert(int data)


{
root = insert(data, root);
}

private AVLNode insert(int data, AVLNode avlNode)


{
if (avlNode == null)
avlNode = new AVLNode(data);
else if (data < [Link])
{
[Link] = insert(data, [Link]);
if (height([Link]) - height([Link]) == 2)
if (data < [Link])
avlNode = leftRotation(avlNode);
else
avlNode = leftRightRotation(avlNode);
} else if (data > [Link])
{
[Link] = insert(data, [Link]);
if (height([Link]) - height([Link]) == 2)
if (data > [Link])
avlNode = rightRotation(avlNode);
else
avlNode = rightLeftRotation(avlNode);
} else
;
[Link] = max(height([Link]), height([Link])) + 1;
return avlNode;
}

private AVLNode leftRotation(AVLNode avlNode)


{
AVLNode k1 = [Link];
[Link] = [Link];
[Link] = avlNode;
[Link] = max(height([Link]), height([Link])) + 1;
[Link] = max(height([Link]), [Link]) + 1;
return k1;
}

private AVLNode rightRotation(AVLNode avlNode)


{
AVLNode node = [Link];
[Link] = [Link];
[Link] = avlNode;
[Link] = max(height([Link]), height([Link])) + 1;
[Link] = max(height([Link]), [Link]) + 1;
return node;
}

private AVLNode leftRightRotation(AVLNode avlNode)


{
[Link] = rightRotation([Link]);
return leftRotation(avlNode);
}

private AVLNode rightLeftRotation(AVLNode avlNode)


{
[Link] = leftRotation([Link]);
return rightRotation(avlNode);
}

public int countNodes()


{
return countNodes(root);
}

private int countNodes(AVLNode avlNode)


{
if (avlNode == null)
return 0;
else
{
int l = 1;
l += countNodes([Link]);
l += countNodes([Link]);
return l;
}
}

public boolean search(int data)


{
return search(root, data);
}

private boolean search(AVLNode avlNode, int data)


{
boolean found = false;
while ((avlNode != null) && !found)
{
int rval = [Link];
if (data < rval)
avlNode = [Link];
else if (data > rval)
avlNode = [Link];
else
{
found = true;
break;
}
found = search(avlNode, data);
}
return found;
}

public void inorder() {


inorder(root);
}

private void inorder(AVLNode avlNode)


{
if (avlNode != null)
{
inorder([Link]);
[Link]([Link] + " ");
inorder([Link]);
}
}
}

import [Link];

public class AVLTreeHelper


{
public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);
AVLTree avlTree = new AVLTree();
char ch;
do
{
[Link]("\nAVLTree Operations\n");
[Link]("1. insert ");
[Link]("2. search");
[Link]("3. count nodes");
int choice = [Link]();
switch (choice)
{
case 1:
[Link]("Enter integer element to insert");
[Link]([Link]());
break;
case 2:
[Link]("Enter integer element to search");
[Link]("Search result : " + [Link]([Link]()));
break;
case 3:
[Link]("Nodes = " + [Link]());
break;
default:
[Link]("Wrong Entry \n ");
break;
}

[Link]("\nIn order : ");


[Link]();

[Link]("\nDo you want to continue (Type y or n) \n");


ch = [Link]().charAt(0);
} while (ch == 'Y' || ch == 'y');
}
}

Common questions

Powered by AI

The height of a node in an AVL Tree is updated after each insertion or rotation by setting it to one plus the maximum height of its left and right subtrees. This update ensures that the tree reflects any height changes due to insertions or rotations, allowing the balance factor to be calculated accurately for maintaining the tree's self-balancing properties .

A double rotation, which includes left-right and right-left rotations, is used in AVL trees to handle cases where a simple rotation is not sufficient to maintain balance. The left-right rotation is applied when a tree is unbalanced with a left child that has a right-heavy subtree. It involves a right rotation on the left child, followed by a left rotation on the root node. The right-left rotation is the mirror process, starting with a left rotation on the right child, followed by a right rotation on the root node. These rotations rebalance the tree, ensuring that the balance factor rules are maintained .

The `countNodes` function in an AVL Tree counts and returns the total number of nodes in the tree. It does this by recursively traversing the entire tree, adding one for each node visited, thereby enabling the tree to provide information about its size. This function is straightforward since it only requires a complete traversal of the nodes to compute the total count .

The primary advantage of an AVL tree over a traditional Binary Search Tree (BST) is its automatic self-balancing trait that maintains a logarithmic height, leading to consistently efficient operations like lookup, insertion, and deletion at O(log n) complexity. However, this self-balancing feature comes at the cost of additional complexity in the form of rotations which can increase insertion and deletion times. For applications with frequent insertions and deletions, this overhead might pose a potential drawback compared to the simpler implementation of a BST which does not incur rotation costs .

A right rotation in an AVL tree is performed when a node becomes left-heavy, typically occurring during node insertions or deletions that increase the height of the left subtree compared to the right by more than one level. This scenario arises when the balance factor becomes less than -1 due to a longer left subtree. The right rotation shifts nodes around to decrease the left subtree's height and increase the right subtree's height, thereby restoring balance by ensuring the balance factor stays within the acceptable range of -1 to 1 .

The AVL Tree ensures efficient searching by maintaining a balanced structure through self-balancing operations like rotations. This balance keeps the tree's height logarithmic relative to the number of nodes, ensuring that searching remains efficient with a complexity of O(log n). In contrast, a non-balanced Binary Search Tree can degenerate into a linked list in the worst-case scenarios, leading to linear search times of O(n) as it becomes skewed by sequence insertions .

The balance factor in an AVL Tree is crucial because it ensures that the tree remains approximately balanced at all times, which guarantees logarithmic height and thus ensures that tree operations such as insertion, deletion, and lookup remain efficient. The balance factor of a node is defined as the difference between the heights of its right and left subtrees (height(right) - height(left)), and can only be 1, 0, or -1. If the balance factor falls outside this range after an insertion or deletion, the tree performs rotations (right, left, left-right, right-left) to rebalance itself .

The `search` function in the AVLTree class ensures a boolean return value by traversing the tree from the root, comparing the search data with the node's data. If the data is found, the function returns true. If the search data is less, it goes to the left child; if more, to the right child. The traversal continues until the node's data matches the search data, or the traversal reaches a null node, in which case it returns false, indicating the data is not present .

The `insert` function in an AVL tree first places the new node according to the Binary Search Tree property. After insertion, it checks the balance factor of the node and its ancestors to identify any imbalances. If an imbalance is detected (balance factor greater than 1 or less than -1), the tree rebalances itself by performing necessary rotations (right, left, left-right, or right-left rotations) until the balance factor is restored to values between -1 and 1 at all nodes .

The in-order traversal process in an AVL Tree is a depth-first traversal method that visits nodes in ascending order. It starts at the root, traverses the left subtree, visits the root, and then traverses the right subtree. This process is significant because it results in visiting nodes in a sorted order, which is very useful in applications that require output of data in a sequential, sorted manner. The AVL Tree's balance ensures that traversal operations are efficient, maintaining the O(n) complexity typical of in-order traversal .

AVL Tree
AVL tree is a self-balancing Binary Search Tree (BST) where the difference between heights of 
left and right subtre
Left-Right Rotation
                                                    
Right-Left Rotation
data = n;
        height = 0;
    }
}
// AVL Tree Class
class AVLTree 
{
    private AVLNode root;
    public AVLTree
; 
        avlNode.height = max(height(avlNode.left), height(avlNode.right)) + 1;
        return avlNode;
    }
    p
}
    public boolean search(int data) 
   {
        return search(root, data);
    }
    
    private boolean search(AVLN
char ch;
        do 
        {
            System.out.println("
AVLTree Operations
");
            System.out.print

You might also like