Advertisement
Guest User

Untitled

a guest
Nov 20th, 2019
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.96 KB | None | 0 0
  1. import java.util.*;
  2. public class BST{
  3.     int data;
  4.     BST left, right;
  5.     BST(int x){
  6.         this.left=this.right=null; data=x;
  7.     }
  8.     public void insert(int i){
  9.         if(i<=data){
  10.             if(left!=null)
  11.             right.insert(i);
  12.             else
  13.             left = new BST(i);
  14.            
  15.         }
  16.         else if (i>=data){
  17.             if (right!=null)
  18.             right.insert(i);
  19.             else right = new BST(i);
  20.            
  21.         }
  22.     }
  23.     public void inOrder(BST tree){
  24.         if(tree!=null){
  25.             inOrder(tree.left);
  26.             System.out.print(tree.data+" ");
  27.             inOrder(tree.right);
  28.         }
  29.     }
  30.     public void preOrder(BST tree){
  31.         if (tree!= null){
  32.             System.out.print(tree.data+" ");
  33.             preOrder(tree.left);
  34.             preOrder(tree.right);
  35.         }
  36.     }
  37.     public void postOrder(BST tree){
  38.         if (tree!=null){
  39.             postOrder(tree.left);
  40.             postOrder(tree.right);
  41.             System.out.print(tree.data+" ");
  42.            
  43.         }
  44.     }
  45.     public void BFS(BST tree){ // Printing Breadth-First
  46.        System.out.print(tree.data);
  47.        
  48.     }
  49.     public static void main(String args[]){
  50.         char cho; int n;
  51.         Scanner sc = new Scanner(System.in);
  52.         System.out.print("Enter the root node ");
  53.         n=sc.nextInt();
  54.         BST ob = new BST(n);
  55.         System.out.print("enter ur choice y or n =  ");
  56.         cho =sc.next().charAt(0);
  57.         while(cho == 'y'){
  58.             System.out.print("enter node value");
  59.             n =sc.nextInt();
  60.             ob.insert(n);
  61.             System.out.print("enter ur choice y or n ");
  62.             cho =sc.next().charAt(0);
  63.         }
  64.         System.out.print("inorder traversal");
  65.         ob.inOrder(ob);
  66.         System.out.print("preorder traversal");
  67.         ob.preOrder(ob);
  68.         System.out.print("inorder traversal");
  69.         ob.postOrder(ob);
  70.        
  71.     }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement