Wednesday, February 19, 2014

B-TREE


PROGRAM:

import java.io.*;
class Node
{
Node left;
Node right;
int value;
public Node(int value)
{
this.value = value;
}
}
public class BTree
{
public static void main(String[] args)throws Exception
{
Node rootnode = new Node(25);
Operation op = new Operation();;
System.out.println("Building tree with rootvalue"+rootnode.value);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the no of nodes");
String size=br.readLine();
int si=Integer.parseInt(size);
for(int i=0;i<si;i++)
{
System.out.println("Enter the element");
String element=br.readLine();
int elements=0;
elements=Integer.parseInt(element);
op.insert(rootnode,elements);
System.out.println("Traversing tree in order");
op.printInOrder(rootnode);
}
}
}
class Operation{
static void insert(Node node, int value)
{
if (value < node.value)
{
if (node.left != null)
{
insert(node.left, value);
}
else
{
System.out.println("  Inserted " + value +" to left of node " + node.value);
node.left = new Node(value);
}
}
else if (value > node.value)
{
if (node.right != null)
{
insert(node.right, value);
}
else
{
System.out.println(" Inserted " + value + " to right of node " + node.value);
node.right = new Node(value);
}
}
}
public void printInOrder(Node node)
{
if (node != null)
{
printInOrder(node.left);
System.out.println("  Traversed " + node.value);
printInOrder(node.right);
}
}
}




OUTPUT:


C:\Program Files\Java\jdk1.5.0_01\bin>java BTree
Building tree with rootvalue25
Enter the no of nodes
4
Enter the element
25

Traversing tree in order:
Traversed 25
Enter the element
12
            Inserted 12 to left of node 25

Traversing tree in order:
Traversed 12
           Traversed 25
Enter the element
36
Inserted 36 to right of node 25

Traversing tree in order
Traversed 12
Traversed 25
Traversed 36
Enter the element



No comments:

Post a Comment