TOPIC: BINARY SEARCH TREE-PRE,MID,POST TRAVERSAL METHODS.
DATE:6/9/2012
*/
import java.util.*;
import java.io.*;
class Nodetype
{
int info;
Nodetype next,right,left,father ;
Nodetype ()
{ //"the default info value is 03"
this(3);
}
Nodetype (int i)
{
info = i ;
left= null;
right=null;
father=null;
}
}
class Operations
{
Nodetype maketree(int x)
{
Nodetype node=new Nodetype(x);
return(node);
}
void setleft(Nodetype p,int x)
{
if(p==null)
System.out.println("Invalid insertion");
else
if(p.left!=null)
System.out.println("Invalid insertion");
else
p.left=maketree(x);
}
void setright(Nodetype p,int x)
{
if(p==null)
System.out.println("Invalid insertion");
else
if(p.right!=null)
System.out.println("Invalid insertion");
else
p.right=maketree(x);
}
void intrav(Nodetype ptree)
{
if(ptree!=null)
{ System.out.println();
intrav(ptree.left);
System.out.println(ptree.info+" ");
intrav(ptree.right);
}
}
void pretrav(Nodetype ptree)
{
if(ptree!=null)
{ System.out.println();
System.out.println(ptree.info+" ");
pretrav(ptree.left);
pretrav(ptree.right);
}
}
void postrav(Nodetype ptree)
{
if(ptree!=null)
{ System.out.println();
postrav(ptree.left);
postrav(ptree.right);
System.out.println(ptree.info+" ");
}
}
void create() throws Exception
{
BufferedReader br = new BufferedReader ( new InputStreamReader(System.in));
Nodetype ptree,p,q;
int n,number=0;
System.out.println(" Enter no. of nodes:");
n=Integer.parseInt(br.readLine());
System.out.println("enter info for"+n+" nodes:");
number=Integer.parseInt(br.readLine());
ptree=maketree(number);
for(int i=1;i<n;i++)
{
number=Integer.parseInt(br.readLine());
p=q=ptree;
while(q!=null && number!=p.info)
{
p=q;
if(number<p.info)
q=p.left;
else
q=p.right;
}
if(number==p.info)
System.out.println(number+" is duplicate");
else
if(number<p.info)
setleft(p,number);
else
setright(p,number);
}
System.out.println("Inorder traversal:");
intrav(ptree);
System.out.println("preorder traversal: ");
pretrav(ptree);
System.out.println("postorder traversal: ");
postrav(ptree);
}
}
class Demo
{
public static void main(String args[])throws Exception
{
Operations op=new Operations();
op.create();
System.out.println("thank u coded by TG");
}
}
/*
OUTPUT:
java Demo
Enter no. of nodes:
13
enter info for13 nodes:
8
3
1
5
6
7
11
9
10
14
12
13
15
Inorder traversal:
1 3 5 6 7 8 9 10 11 12 13 14 15
preorder traversal:
8 3 1 5 6 7 11 9 10 14 12 13 15
postorder traversal:
1 7 6 5 3 10 9 13 12 15 14 11 8
thank u coded by TG
*/
No comments:
Post a Comment