Preview:
import java.util.*;
public class BinarySearchTree
{
class Node
{ int key;
Node left, right;
public Node(int data)
{ key = data;
left = right = null;
}
}
private Node root;
public BinarySearchTree()
{ root=null; }
public void insert(int data)
{ root = insertRec(root, data); }
private Node insertRec(Node root,int key)
{ if (root == null) 
{ root = new Node(key);
return root;
}
if (key < root.key) 
root.left = insertRec(root.left, key);
else if (key > root.key) 
root.right = insertRec(root.right, key);
return root;
}
public void inorder()
{ inorderRec(root); }
private void inorderRec(Node root)
{
if (root != null) {
inorderRec(root.left);
System.out.print(root.key + " ");
inorderRec(root.right);
}
}
public void preorder()
{ preorderrec(root); }
private void preorderrec(Node node)
{
if (node == null)
return;
System.out.print(node.key + " ");
preorderrec(node.left);
preorderrec(node.right);
}
public void postorder()
{ postorderrec(root); }
private void postorderrec(Node node)
{
if (node == null)
return;
postorderrec(node.left);
postorderrec(node.right);
System.out.print(node.key + " ");
}
public static void main(String[] args) 
{
Scanner sc = new Scanner(System.in);
BinarySearchTree bst = new BinarySearchTree();
String ch="";
do{
System.out.print("Enter the element to be inserted in the tree: ");
int n=sc.nextInt();
sc.nextLine();
bst.insert(n);
System.out.print("Do you want to insert another element? (Say 'yes'): ");
ch = sc.nextLine();
}while(ch.equals("yes"));
System.out.print("Inorder Traversal : The elements in the tree are: ");
bst.inorder();
System.out.println();
System.out.print("Preorder Traversal : The elements in the tree are: ");
bst.preorder();
System.out.println();
System.out.print("Postorder Traversal : The elements in the tree are: ");
bst.postorder();
System.out.println();
}
}
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter