class Tree {
Tree left, right;
int item;
public Tree(Tree left, Tree right, int item) {
this.left = left;
this.right = right;
this.item = item;
}
}
public class BinSearchTree {
/**
* @param args
*/
public void insert(Tree root, int item) {
Tree p = new Tree(null, null, item);
if (root == null) {
root = p;
}
while (true) {
if (root.item == item)
return;
if (root.item > item) {
if (root.left == null) {
root.left = p;
return;
} else {
root = root.left;
}
} else {
if (root.right == null) {
root.right = p;
return;
} else {
root = root.right;
}
}
}
}
public void inorderTraversal(Tree root) {
if(root==null)
return;
if (root.left != null)
inorderTraversal(root.left);
System.out.print(root.item + " ");
if (root.right != null)
inorderTraversal(root.right);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
BinSearchTree bst = new BinSearchTree();
Tree tree = null;
int a[] = { 12, 1, 3, 4, 14, 15, 19, 7, 9, 20 };
tree= new Tree(null,null,a[0]);
for (int i = 1; i < a.length; i++) {
bst.insert(tree, a[i]);
}
bst.inorderTraversal(tree);
}
}