AVL Tree

Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

K L UNIVERSITY

FRESHMAN ENGINEERING DEPARTMENT


A Project Based Lab Report

On

AVL Tree

SUBMITTED BY:

I.D NUMBER NAME

190032070 V. SUBHASH

190032076 M. CHANDRAMANI VARMA

190032078 M.CHANDRA SEKHAR

UNDER THE ESTEEMED GUIDANCE OF

CH.NARESH

<Assistant Professor>

KL UNIVERSITY
Green fields, Vaddeswaram – 522 502
DEPARTMENT OF BASIC ENGINEERING SCIENCES

CERTIFICATE

This is to certify that the project based laboratory report entitled


submitted by Mr. V.SUBHASH, M.CHANDRAMANI VARMA,M.CHANDRA SEKHAR
bearingRegd.No.190032070,190032076, 190032078 to the Department of Basic
Engineering Sciences, KL University in partial fulfillment of the requirements
for the completion of a project in “Data Structures” course in I B Tech II Semester,
is a bonafide record of the work carried out by him/her under my supervision
during the academic year 2019-20.

PROJECT SUPERVISOR HEAD OF THE DEPARTMENT

CH.NARESH Dr. D.HARITHA


ACKNOWLEDGEMENTS

It is great pleasure for us to express my gratitude to our honorable


President Sri. Koneru Satyanarayana, for giving the opportunity and platform
with facilities in accomplishing the project based laboratory report.

I express the sincere gratitude to our director Dr. A Jagadeesh for his
administration towards our academic growth.

I express sincere gratitude to our Coordinator and HOD-BES Dr. D.Haritha


for her leadership and constant motivation provided in successful completion of
our academic semester. I record it as my privilege to deeply thank for providing
us the efficient faculty and facilities to make our ideas into reality.

I express my sincere thanks to our project supervisor CH.NARESH for his


novel association of ideas, encouragement, appreciation and intellectual zeal
which motivated us to venture this project successfully.

Finally, it is pleased to acknowledge the indebtedness to all those who


devoted themselves directly or indirectly to make this project report success.

190032070 V.SUBHASH

190032076 M.CHANDRAMAVARMA

190032078 M.CHANDRA SEKHAR


ABSTRACT

AVL tree implements the Map abstract data type just like a regular
binary search tree, the only difference is in how the tree performs. To
implement our AVL tree we need to keep track of a balance factor for
each node in the tree. We do this by looking at the heights of the left and
right subtrees for each node..
INDEX
S.NO TITLE PAGE NO

1 Introduction 6-7

2 Aim of the Project 8

2.1 Advantages & Disadvantages 9

2.2 Future Implementation 9

3 Software & Hardware Details 9

4 Class Diagram 10

5 Implementation 11-42

6 Outputs/ScreenShots 43-46

7 Conclusion 47
INTRODUCTION

The AVL trees, also called "Height Balanced Trees" were first
introduced by two Russians named Adelson-Velskii and Landis. AVL
trees are maintained in such a way that the trees always remain within
one level of being perfectly balanced. ... The BALANCE FACTOR of a
node T in a binary tree bf(T) = h-L - h-R.

AVL tree is a self-balanced binary search tree. That means, an AVL tree
is 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 for every node, height of its children differ by at
most one. In an AVL tree, every node maintains an extra information
known as balance factor to take care of the self-balancing nature of the
tree.
AIM
To Implement AVL tree and its operations using java

Advantages:-
1. Since AVL trees are height balance trees, operations like insertion and deletion
have low time complexity. Let us consider an example:

2. To insert a node with a key Q in the binary tree, the algorithm requires seven
comparisons, but if you insert the same key in AVL tree, from the above 1st figure,
you can see that the algorithm will require three comparisons.

Disadvantages:-

1. Slow Inserts and Deletes


The largest disadvantage to using an AVL tree is the fact that in the event that it is slightly
unbalanced it can severely impact the amount of time that it takes to perform inserts and
deletes.

2. Fast Updating Systems


In the event that you’re working on a system that has the tendency to update quickly then it is
advisable to avoid AVL trees.

Future enhancements:-
AVL tree (height-balanced tree) A binary search tree such that for each node the
heights of the left and right subtrees differ by at most one. ... During insertion or
deletion, a node in an AVL tree may become critical or unbalanced and then the
tree has to be reorganized to maintain its balanced property.
SYSTEM REQUIREMENTS

⮚ SOFTWARE REQUIREMENTS:
The major software requirements of the project are as follows:
Language : Java
IDE : Eclipse
Operating system: Windows Xp or later.

⮚ HARDWARE REQUIREMENTS:
The hardware requirements that map towards the software are as follows:

RAM : 8 Gb or More.

Processor :Intel i5 8th gen and higher (or)Ryzen 5 or higher.


CLASS DIAGRAM
IMPLEMENTATION
import
java.io.*;

import java.util.*;

public class AVLTree {

public void print(Node root) {


// TODO Auto-generated method stub

public Node deleteNode(Node root, int parseInt) {


// TODO Auto-generated method stub
return null;
}

public Node insert(Node root, int parseInt) {


// TODO Auto-generated method stub
return null;
}

public class Node {

private Node left, right, parent;

private int height = 1;

private int value;

private Node (int val) {

this.value = val;

private int height (Node N) {


if (N == null)

return 0;

return N.height;

private Node insert(Node node, int value) {

/* 1. Perform the normal BST rotation */

if (node == null) {

return(new Node(value));

if (value < node.value)

node.left = insert(node.left, value);

else

node.right = insert(node.right, value);

/* 2. Update height of this ancestor node */

node.height = Math.max(height(node.left), height(node.right)) + 1;

/* 3. Get the balance factor of this ancestor node to check whether

this node became unbalanced */

int balance = getBalance(node);

// If this node becomes unbalanced, then there are 4 cases

// Left Left Case

if (balance > 1 && value < node.left.value)


return rightRotate(node);

// Right Right Case

if (balance < -1 && value > node.right.value)

return leftRotate(node);

// Left Right Case

if (balance > 1 && value > node.left.value)

node.left = leftRotate(node.left);

return rightRotate(node);

// Right Left Case

if (balance < -1 && value < node.right.value)

node.right = rightRotate(node.right);

return leftRotate(node);

/* return the (unchanged) node pointer */

return node;

private Node rightRotate(Node y) {

Node x = y.left;

Node T2 = x.right;
// Perform rotation

x.right = y;

y.left = T2;

// Update heights

y.height = Math.max(height(y.left), height(y.right))+1;

x.height = Math.max(height(x.left), height(x.right))+1;

// Return new root

return x;

private Node leftRotate(Node x) {

Node y = x.right;

Node T2 = y.left;

// Perform rotation

y.left = x;

x.right = T2;

// Update heights

x.height = Math.max(height(x.left), height(x.right))+1;

y.height = Math.max(height(y.left), height(y.right))+1;

// Return new root

return y;
}

// Get Balance factor of node N

private int getBalance(Node N) {

if (N == null)

return 0;

return height(N.left) - height(N.right);

public void preOrder(Node root) {

if (root != null) {

preOrder(root.left);

System.out.printf("%d ", root.value);

preOrder(root.right);

private Node minValueNode(Node node) {

Node current = node;

/* loop down to find the leftmost leaf */

while (current.left != null)

current = current.left;

return current;

private Node deleteNode(Node root, int value) {

// STEP 1: PERFORM STANDARD BST DELETE


if (root == null)

return root;

// If the value to be deleted is smaller than the root's value,

// then it lies in left subtree

if ( value < root.value )

root.left = deleteNode(root.left, value);

// If the value to be deleted is greater than the root's value,

// then it lies in right subtree

else if( value > root.value )

root.right = deleteNode(root.right, value);

// if value is same as root's value, then This is the node

// to be deleted

else {

// node with only one child or no child

if( (root.left == null) || (root.right == null) ) {

Node temp;

if (root.left != null)

temp = root.left;

else

temp = root.right;

// No child case
if(temp == null) {

temp = root;

root = null;

else // One child case

root = temp; // Copy the contents of the non-empty child

temp = null;

else {

// node with two children: Get the inorder successor (smallest

// in the right subtree)

Node temp = minValueNode(root.right);

// Copy the inorder successor's data to this node

root.value = temp.value;

// Delete the inorder successor

root.right = deleteNode(root.right, temp.value);

// If the tree had only one node then return

if (root == null)

return root;

// STEP 2: UPDATE HEIGHT OF THE CURRENT NODE


root.height = Math.max(height(root.left), height(root.right)) + 1;

// STEP 3: GET THE BALANCE FACTOR OF THIS NODE (to check whether

// this node became unbalanced)

int balance = getBalance(root);

// If this node becomes unbalanced, then there are 4 cases

// Left Left Case

if (balance > 1 && getBalance(root.left) >= 0)

return rightRotate(root);

// Left Right Case

if (balance > 1 && getBalance(root.left) < 0) {

root.left = leftRotate(root.left);

return rightRotate(root);

// Right Right Case

if (balance < -1 && getBalance(root.right) <= 0)

return leftRotate(root);

// Right Left Case

if (balance < -1 && getBalance(root.right) > 0) {

root.right = rightRotate(root.right);

return leftRotate(root);

}
return root;

public void print(Node root) {

if(root == null) {

System.out.println("(XXXXXX)");

return;

int height = root.height,

width = (int)Math.pow(2, height-1);

// Preparing variables for loop.

List<Node> current = new ArrayList<Node>(1),

next = new ArrayList<Node>(2);

current.add(root);

final int maxHalfLength = 4;

int elements = 1;

StringBuilder sb = new StringBuilder(maxHalfLength*width);

for(int i = 0; i < maxHalfLength*width; i++)

sb.append(' ');

String textBuffer;
// Iterating through height levels.

for(int i = 0; i < height; i++) {

sb.setLength(maxHalfLength * ((int)Math.pow(2, height-1-i) - 1));

// Creating spacer space indicator.

textBuffer = sb.toString();

// Print tree node elements

for(Node n : current) {

System.out.print(textBuffer);

if(n == null) {

System.out.print(" ");

next.add(null);

next.add(null);

} else {

System.out.printf("(%6d)", n.value);

next.add(n.left);

next.add(n.right);

}
System.out.print(textBuffer);

System.out.println();

// Print tree node extensions for next level.

if(i < height - 1) {

for(Node n : current) {

System.out.print(textBuffer);

if(n == null)

System.out.print(" ");

else

System.out.printf("%s %s",

n.left == null ? " " : "/", n.right == null ? " " : "\\");

System.out.print(textBuffer);

System.out.println();

// Renewing indicators for next run.


elements *= 2;

current = next;

next = new ArrayList<Node>(elements);

public static void main(String args[]) {

AVLTree t = new AVLTree();

Node root = null;

while (true) {

System.out.println("(1) Insert");

System.out.println("(2) Delete");

try {

BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));

String s = bufferRead.readLine();

if (Integer.parseInt(s) == 1) {

System.out.print("Value to be inserted: ");

root = t.insert(root, Integer.parseInt(bufferRead.readLine()));

else if (Integer.parseInt(s) == 2) {

System.out.print("Value to be deleted: ");

root = t.deleteNode(root, Integer.parseInt(bufferRead.readLine()));

}
else {

System.out.println("Invalid choice, try again!");

continue;

t.print(root);

catch(IOException e) {

e.printStackTrace();

}
OUTPUTS
Screen Shots:
CONCLUSION
AVL trees are often compared with red–black trees because both

support the same set of operations and take time for the basic operations. For
lookup-intensive applications, AVL trees are faster than red–black trees because
they are more strictly balanced.[4] Similar to red–black trees, AVL trees are height-

balanced. Both are, in general, neither weight-balanced nor -balanced for any

;[5] that is, sibling nodes can have hugely differing numbers of descendants.

The algorithm for intersection or difference is similar, but requires the Join2 helper
routine that is the same as Join but without the middle key. Based on the new
functions for union, intersection or difference, either one key or multiple keys can be
inserted to or deleted from the AVL tree. Since Split calls Join but does not deal with
the balancing criteria of AVL trees directly, such an implementation is usually called
the "join-based" implementation.

You might also like