0% found this document useful (0 votes)
34 views

An Introduction To AVL Tree and Implementation in JAVA: Sinan BAKIR April 8, 2009

This document introduces AVL trees, a self-balancing binary search tree. It discusses AVL tree insertion and search algorithms, and provides a Java implementation of an AVL tree with methods for insertion, searching, checking balance, and rotating nodes. The implementation is used to search a file of values to determine which values are contained in another file, writing the results to an output file.

Uploaded by

Anas Farhan
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

An Introduction To AVL Tree and Implementation in JAVA: Sinan BAKIR April 8, 2009

This document introduces AVL trees, a self-balancing binary search tree. It discusses AVL tree insertion and search algorithms, and provides a Java implementation of an AVL tree with methods for insertion, searching, checking balance, and rotating nodes. The implementation is used to search a file of values to determine which values are contained in another file, writing the results to an output file.

Uploaded by

Anas Farhan
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

An Introduction to AVL Tree and

Implementation in JAVA
Sinan BAKIR
April 8, 2009

Abstract
An AVL tree is a special kind of binary search tree that has a self
balancing property. In this article you will find out ;
• What an AVL Tree is
• Insertion and Search algorithms for an AVL Tree
• A Java implementation of AVL Tree

1
1 Introduction
What is a tree? It is a general use data structure with a set of linked nodes. A
node may contain a value or represents a data on its own , and has a pointer
for its childs. Each node in a tree has zero or more child nodes. A tree t
is a finite nonempty set of elements. One of these elements is called root,
and remaining elements(if any) are partitioned into trees which are called
subtrees of t. The height of a node is the length of the longest downward
path to a leaf from that node. The height of a tree is the length of the longest
downward path to a leaf from the root. What is a binary tree ? A binary
tree is a tree that each node has at most two child. And a binary search tree
is a kind of tree that, each node’s left child is less than it’s value and each
node’s right child is bigger than it’s value.
So what is an AVL Tree? An AVL Tree is a very special kind of tree. Its
is a self balancing tree. It can balance itself so that the searching becomes
faster. It is guaranteed a O(log n) performance for each search tree operation
by ensuring that the search tree height is always O(log n). Think of a binary
search Tree inserted 10 11 12 13 14 15 respectively. Then the height of the
tree will be 6. So when a search for finding 15 in the tree made, it will take
6 unit time. And think of a great data which is inserted to the tree and after
searched for the most depthed node. It will take enormous time. For such
situations AVL tree will be a great solution.

2 Insertion
Insertion for an AVL tree is made by rotations of the branches. Insertion
done same as a binary-search tree. If the current value is less than the node
then insert it to the left, else insert it to the right. After inserting, a check for
the balancing is made. If the tree is wighted to the left then a right rotation
is made, or else a left rotation is made. If the balancing is good then no
rotation made.
Insertion Code
2 hinsertion 2i≡
public Node insert(int n)
{
if(root == null)
{
root = new Node(n);
}
else

2
{
root = insert(root, new Node(n));
}
if(checkAVL(root) == 0){
return root;

}
else if(checkAVL(root) == 1){
root = rotateLeft(root);
return root;
}
else {
root = rotateRight(root);
return root;
}
}

This code is written to file insertion.

3
2.1 Check AVL
You see the function chechAVL in the insertion. Check AVL function con-
sumes a Node and returns an integer. The purpose is to check whether the
node is balanced or not after an insertion. If the depth of the right sub-
tree minus the depth of the left subtree is greater than or equal to 2 then
it returns 1 to rotate the node leftwards. Similarly if the depth of the left
subtree minus the depth of the right subtree is greater than or equal to 2
then it returns -1 to rotate the node rightwards. Otherwise it returns 0 and
it means that no rotation is needed in that situation.
4 hcheckAVL 4i≡
public int checkAVL(Node n)
{
if(depth(n.right) - depth(n.left) >= 2)
{
return 1;
}
else if(depth(n.left) - depth(n.right) >= 2)
{
return -1;
}
else
{
return 0;
}
}

This code is written to file checkAVL.

4
3 Search
Searching of a Avl tree is the same as searching a binary search tree. If the
tree is null, the value that is searching doesn’t exist in the tree. Otherwise,
if the root equals to the value then search is successful and return true. If
the value is less than the root, keep searching to the left subtree. Similarly if
its greater than the root then keep searching to the right subtree, and repeat
this process until the value is found or reaching to the end of the subtree,
meaning reaching to a leaf.

5
Searching Code
6 hsearching 6i≡
public boolean search(int n)
{
Node clone = root;
while(clone != null)
{
if(clone.data == n)
{
return true;
}
else if(clone.data < n)
{
clone = clone.right;
}
else
{
clone = clone.left;
}
}
return false;
}
This code is written to file searching.

6
4 Usage
The purpose of this implementation is to search a file if the file contains the
values of the second file. So the program consumes 3 inputs. One is the file
to be searched. Second is the file of the searching inputs and the third is the
file to be outputted the results. For example there is a file named data.txt
contains 1000 lines of numbers. And there is a file named search.txt that
contains the numbers we want to search in the data.txt. When we input
these 2 files to the program and give a name for the outputted file say re-
sult.txt, it produces a result.txt file which contains the occurances.

We can run the program following way:


javac Main.java && javac Tree.java && javac Node.java
After the compilation following line is executed.
java Main data.txt search.txt result.txt
Then the program inserts the values of data.txt in to the tree and after
searches for the values of the search.txt file and writes the occurances into
the result.txt file.
7 hTree.java 7i≡
/**
* AVL Tree Implementation
* _Istanbul Bilgi University - Computer Science Department
* Author: Sinan Bakır , sinanbakir at gmail.com
*/
class Tree
{
Node root;

public Tree()
{
}

public Tree(Node root)


{
this.root = root;
}

public Node rotateRight()


{
return rotateRight(root);

7
}

public Node rotateRight(Node n)


{
Node q = root;
Node p = q.left;
Node c = q.right;
Node a = p.left;
Node b = p.right;

q = new Node(q.data, b, c);


p = new Node(p.data, a, q);

return p;
}
public Node rotateLeft()
{
return rotateLeft(root);
}
public Node rotateLeft(Node n)
{
Node q =root;
Node p = q.right;
Node c = q.left;
Node a = p.left;
Node b = p.right;

q = new Node(q.data,c,a);
p = new Node(p.data,q,b);

return p;
}

public Node insert(int n)


{
if(root == null)
{
root = new Node(n);
}
else
{

8
root = insert(root, new Node(n));
}
//System.out.println(n);
if(checkAVL(root) == 0){
//System.out.println(checkAVL(root));
return root;

}
else if(checkAVL(root) == 1){
//System.out.println(checkAVL(root));
root = rotateLeft(root);
return root;
}
else {
//System.out.println(checkAVL(root));
root = rotateRight(root);
return root;
}
}

public Node insert(Node n, Node m)


{
if(n == null)
{
return m;
}
if (m.data > n.data) // insert right
{
return new Node(n.data,
n.left,
insert(n.right, m));
}
else // insert left
{
return new Node(n.data,
insert(n.left, m),
n.right);
}
}
public boolean search(int n)

9
{
Node clone = root;
while(clone != null)
{
if(clone.data == n)
{
//System.out.println(clone.data);
return true;
}
else if(clone.data < n)
{
clone = clone.right;
}
else
{
clone = clone.left;
}
}
return false; //throw new Exception("The value doesn’t exist");
}
public int depth()
{
return depth(root);
}
public int depth(Node n)
{
if(n == null)
{
return 0;
}
else
{
return Math.max(depth(n.left),depth(n.right)) + 1;
}
}
public int checkAVL()
{
return checkAVL(root);
}
public int checkAVL(Node n)
{

10
if(depth(n.right) - depth(n.left) >= 2)
{
return 1;
}
else if(depth(n.left) - depth(n.right) >= 2)
{
return -1;
}
else
{
return 0;
}
}
public int minimum(Node n){
Node current,last = null;
current = n;
while(current != null){
last = current;
current = current.left;
}
return last.data;
}
public int minimum()
{
return minimum(root);
}
public int maximum(Node n){
Node current,last = null;
current = root;
while(current != null){
last = current;
current = current.right;
}
return last.data;
}
public int maximum()
{
return maximum(root);
}

public String toString()

11
{
return root.toString();
}

}
This code is written to file Tree.java.

12
13 hNode.java 13i≡
/**
* AVL Tree Implementation
* _
Istanbul Bilgi University - Computer Science Department
* Author: Sinan Bakır , sinanbakir at gmail.com
*/
public class Node
{
int data;
Node left;
Node right;

public Node(int data)


{
this.data = data;
this.left = null;
this.right = null;
}
public Node(){}

public Node(int data, Node left, Node right)


{
this.data = data;
this.left = left;
this.right = right;
}

public static String getAsString(Node n)


{
if (n != null)
{
return n.toString();
}
else
{
return "N";
}
}

public String toString()


{

13
return "(" + getAsString(left) + " " + data + " " + getAsString(right)
}

}
This code is written to file Node.java.

14
15 hMain.java 15i≡
import java.io.*;
import java.util.*;

//Sinan BAKIR
class Main
{
public static void main(String[] args) throws Exception
{
Tree tl = new Tree();

int k = 0; // k for arguments


int i,j; // i for insert j for search
if(k == 0)
{

try
{
BufferedReader insert = new BufferedReader(new FileRead
String thisLine;

while ((thisLine = insert.readLine()) != null)


{
i = Integer.parseInt(thisLine);
//System.out.println(i);
tl.insert(i);
}
k = 1;
}
catch (IOException e) {
System.err.println("Error: " + e);
}

}
if(k==1)
{
try
{
String thisLine2;
BufferedReader search = new BufferedReader(new FileReader(args[

15
BufferedWriter out = new BufferedWriter(new FileWriter(args[2])
while((thisLine2 = search.readLine()) != null)
{
j = Integer.parseInt(thisLine2);
if(tl.search(j))
{
out.write(""+j);
out.write("\n");
}
}
out.close();
}catch (IOException e) {
System.err.println("Error: " + e);
}

System.out.println("Tree looks like: "+tl);


System.out.println("Tree depth: "+tl.depth());

}
}
This code is written to file Main.java.

16a hdata.txt 16ai≡


1
2
3
4
5
6
24
4
This code is written to file data.txt.

16b hsearch.txt 16bi≡


24
4
This code is written to file search.txt.

16c hresult.txt 16ci≡


This code is written to file result.txt.

16
5 Conclusion
We have seen an implementation of an AVL Tree in JAVA. This implemen-
tation is made for only representation and for a small purpose. It can be
extended for many purposes and can be used in many different computer pro-
grams. You can contact me for any reason via e-mail:sinanbakir at gmail.com

6 References
Wikipedia The Free Encyclopedia http://en.wikipedia.org/wiki/Binary_search_
tree
Wikipedia The Free Encyclopedia http://en.wikipedia.org/wiki/AVL_tree

17

You might also like