Thursday, November 5, 2015
Simple Binary Search Tree using Java
Input: List of Intigers
public class BinarySearchTree {
BinarySearchTree left, right;
int data;
public BinarySearchTree(int data) {
System.out.println("newNode "+data);
this.data = data;
left=null;
right=null;
}
public void insertElement(int... element) {
int size=element.length;
for(int i=0; i<size; i++) {
System.out.println(element[i]);
insertElement(this, element[i]);
}
}
public void insertElement(int element) {
insertElement(this,element);
}
private void insertElement(BinarySearchTree T, int element) {
if(element==T.data) {
System.out.println("ERROR: Data already exist");
} else if(T.left == null && T.right ==null) {
if(element<T.data)
T.left=new BinarySearchTree(element);
else
T.right=new BinarySearchTree(element);
} else if(T.left == null) {
if(element<T.data)
T.left=new BinarySearchTree(element);
else
insertElement(T.right, element);
} else if(T.right == null) {
if(element>T.data)
T.right=new BinarySearchTree(element);
else
insertElement(T.left, element);
} else { //Root has both Left and Right
if(element<T.data)
insertElement(T.left, element);
else
insertElement(T.right, element);
}
}
public String PreOrder() {
return PreOrder(new StringBuffer(), this).toString();
}
private StringBuffer PreOrder(StringBuffer sb, BinarySearchTree T) {
if(T!=null) {
PreOrder(sb, T.left);
PreOrder(sb, T.right);
sb.append(T.data).append(", ");
return sb;
} else return sb;
}
public String PostOrder() {
return PostOrder(new StringBuffer(), this).toString();
}
private StringBuffer PostOrder(StringBuffer sb, BinarySearchTree T) {
if(T!=null) {
sb.append(T.data).append(", ");
PreOrder(sb, T.left);
PreOrder(sb, T.right);
return sb;
} else return sb;
}
public String InOrder() {
return InOrder(new StringBuffer(), this).toString();
}
private StringBuffer InOrder(StringBuffer sb, BinarySearchTree T) {
if(T!=null) {
InOrder(sb, T.left);
sb.append(T.data).append(", ");
InOrder(sb, T.right);
return sb;
} else return sb;
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment