Binary Search Tree > Java Program
Binary Search Tree > Java Program
import java.util.Scanner;
class TreeNode
{
TreeNode left,right;
int info;
public TreeNode(int data)
{
info=data;
left=null;
right=null;
}
}
class Operations
{
TreeNode ptree,p,q;
Operations()
{p=q=ptree=null;
}
public void preorder(TreeNode ptree)
{
if(ptree!=null)
{System.out.print(ptree.info + ” “);
preorder(ptree.left);
preorder(ptree.right);
}
}
public void inorder(TreeNode ptree)
{
if(ptree!=null)
{inorder(ptree.left);
System.out.print(ptree.info + ” “);
inorder(ptree.right);
}
}
public void postorder(TreeNode ptree)
{
if(ptree!=null)
{postorder(ptree.left);
postorder(ptree.right);
System.out.print(ptree.info + ” “);
}
}
public void create(int data)
{Scanner sc=new Scanner(System.in);
TreeNode node=new TreeNode(data);
if(ptree==null) ptree=node;
else
{p=q=ptree;
while((q!=null)&&(q.info!=data))
{ p=q;
if(data<q.info)
q=p.left;
else
q=p.right;
}
if(data==p.info) System.out.print(“\nDuplicate”);
else
{if(data<p.info) p.left=node;
else p.right=node;
}
}
}
void display()
{
System.out.print(“\nPre order:”);preorder(ptree);
System.out.print(“\nIn order:”); inorder(ptree);
System.out.print(“\nPost order:”);postorder(ptree);
}
}//end of class
class BSTree
{public static void main(String arg[])
{Scanner sc=new Scanner(System.in);
System.out.print(“\nEnter size of array : “);
int n=sc.nextInt();
int a[]=new int[n];
System.out.print(“\n Enter array elements : “);
for(int i=0;i<n;i++)
a[i]=sc.nextInt();
Operations op=new Operations();
for(int i=0;i<n;i++)
op.create(a[i]);
op.display();
}
}
Comments
Post a Comment