About

Kannur University btech CSE study materials, question papers, syllabus . . .

Thursday, July 4, 2013

S4 - DSA lab -TRAVERSAL IN BINARY SEARCH TREE

/* TRAVERSAL IN BINARY SEARCH TREE*/

import java.io.*;
class Node
{
int data;
Node lef,rig;
Node(int d)
{
data=d;
lef=null;
rig=null;
}
void display()
{
System.out.println(data);
}
}
class Binary
{
DataInputStream nn=new DataInputStream(System.in);
Node root;
Binary()
{
root=null;
}
void insert()
{
try
{
System.out.print("Enter the element:  ");
int d=Integer.parseInt(nn.readLine());
Node n=new Node(d);
Node curr=root,par=root;
if(root==null)
root=n;
else
{
while(1==1)
{
if(curr.data<n.data)
{
par=curr;
curr=curr.rig;
if(curr==null)
{
par.rig=n;
break;
}
}
else
{
par=curr;
curr=curr.lef;
if(curr==null)
{
par.lef=n;
break;
}
}
}}}
catch(Exception e)
{}
}
void traverse()
{
System.out.println("Inorder");
io(root);
System.out.println("preorder");
pre(root);
System.out.println("postorder");
post(root);
}
void io(Node curr)
{
if(curr!=null)
{
io(curr.lef);
curr.display();
io(curr.rig);
}
}
void pre(Node curr)
{
if(curr!=null)
{
curr.display();
pre(curr.lef);
pre(curr.rig);
}
}

void post(Node curr)
{
if(curr!=null)
{
post(curr.lef);
post(curr.rig);
curr.display();
}
}
}

class Bst
{
public static void main(String args[])throws Exception
{
int p;
Binary b=new Binary();
do
{
DataInputStream get=new DataInputStream(System.in);
System.out.println("\n1.insert\n2.trversal");
System.out.print("Enter the choice: ");
int ch=Integer.parseInt(get.readLine());
p=ch;
switch(ch)
{
case 1 : b.insert();break;
case 2 : b.traverse();break;
}
}while(p<4);
}
}





OUTPUT

1.insert
2.trversal
Enter the choice: 1
Enter the element:  2

1.insert
2.trversal
Enter the choice: 1
Enter the element:  1

1.insert
2.trversal
Enter the choice: 1
Enter the element:  3

1.insert
2.trversal
Enter the choice: 2
Inorder
1
2
3
preorder
2
1
3
postorder
1
3
2

1.insert
2.trversal
Enter the choice:4



0 comments:

Post a Comment