Monday, January 31, 2011

Java program to implement Binary Search Tree

A very generic Binary Search Tree implementation in Java


package lab.tree;

import lab.general.Processable;


public class Tree {

public TreeNode root;

public Tree()
{
root=null;
}

public void insert(Object info)
{

Comparable compdata;

compdata=(Comparable)info;

TreeNode newnode=new TreeNode();
newnode.data=info;



if(root==null)
{
root=newnode;
root.left=null;
root.right=null;
return;

}

TreeNode tmpnode;
tmpnode=root;
while(tmpnode!=null)
{
if((compdata.compareTo(tmpnode.data))<0 )
{
if(tmpnode.left==null)
{
tmpnode.left=newnode;
return;
}
else
{
tmpnode=tmpnode.left;
}

}
else
{
if(tmpnode.right==null)
{
tmpnode.right=newnode;
return;
}
else
{
tmpnode=tmpnode.right;
}
}
}
}




public void inorder(TreeNode rootnode)
{
  if(rootnode !=null)
  {
 Processable info;

 inorder(rootnode.left);
      info=(Processable)rootnode.data;
      info.process();
      inorder(rootnode.right);
 }

 
}

public void preorder(TreeNode rootnode)
{
  if(rootnode !=null)
  {
 Processable info;

 info=(Processable)rootnode.data;
      info.process();
 preorder(rootnode.left);
      preorder(rootnode.right);
 }

  
}


public void postorder(TreeNode rootnode)
{
  if(rootnode !=null)
  {
 Processable info;

 postorder(rootnode.left);
      postorder(rootnode.right);
      info=(Processable)rootnode.data;
      info.process();
 }

 
}







}

No comments: