Binary Tree Implementation:
import java.io.*;
import java.util.*;
class BST{
Node root;
class Node{
int data;
Node left,right;
Node(int data){
this.data=data;
this.left=this.right=null;
public void insert(int data){
if(root==null)
root=new Node(data);
else
insert_rec(root,data);
public Node insert_rec(Node root,int data){
Queue<Node> q= new LinkedList<>();
q.add(root);
while(!q.isEmpty()){
Node top=q.poll();
if(top.left==null){
top.left=new Node(data);
break;
}else
q.add(top.left);
if(top.right==null){
top.right=new Node(data);
break;
}else
q.add(top.right);
return root;
public void inorder(){
inorder_rec(root);
public void inorder_rec(Node root){
if(root==null)
return;
else{
inorder_rec(root.left);
System.out.print(root.data+" ");
inorder_rec(root.right);
public void preorder(){
preorder_rec(root);
public void preorder_rec(Node root){
if(root==null)
return;
else{
System.out.print(root.data+" ");
preorder_rec(root.left);
preorder_rec(root.right);
public void postorder(){
postorder_rec(root);
public void postorder_rec(Node root){
if(root==null)
return;
else{
postorder_rec(root.left);
postorder_rec(root.right);
System.out.print(root.data+" ");
public void levelorder(){
levelorder_rec(root);
System.out.println();
public void levelorder_rec(Node root){
if(root==null){
return;
Queue<Node> q=new LinkedList<>();
q.add(root);
while(!q.isEmpty()){
Node p=q.poll();
System.out.print(p.data+" ");
if(p.left!=null){
q.add(p.left);
if(p.right!=null){
q.add(p.right);
public static void main(String ar[]){
Scanner sc=new Scanner(System.in);
BST t=new BST();
int n=sc.nextInt();
for(int i=0;i<n;i++){
t.insert(sc.nextInt());
}
boolean k=true;
while(k){
System.out.print("\nEnter your choice: ");
int c=sc.nextInt();
switch(c){
case 1:
System.out.print("Inorder: ");
t.inorder();
break;
case 2:
System.out.print("Preorder: ");
t.preorder();
break;
case 3:
System.out.print("Postorder: ");
t.postorder();
break;
case 4:
System.out.print("Level order traversal: ");
t.levelorder();
break;
case 5:
System.out.print("Exiting");
k=false;
break;