safriansah

bst

Aug 3rd, 2018
8,019
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.37 KB | None | 0 0
  1. import java.util.Scanner;
  2. public class tree{
  3.     static Scanner in=new Scanner(System.in);
  4.     public void insert(node a, int b){
  5.         if(b<a.value){
  6.             if(a.left!=null) insert(a.left,b);
  7.             else{
  8.                 a.left=new node();
  9.                 a.left.input(b);
  10.                 System.out.println(b+" di kiri  "+a.value);
  11.             }
  12.         }
  13.         else if(b>a.value){
  14.             if(a.right!=null) insert(a.right,b);
  15.             else{
  16.                 a.right=new node();
  17.                 a.right.input(b);
  18.                 System.out.println(b+" di kanan "+a.value);
  19.             }
  20.         }
  21.     }
  22.     public void view(node a){
  23.         System.out.print("Pre Order  : ");
  24.         preOrder(a);
  25.         System.out.println(" ");
  26.     }  
  27. public void preOrder(node a){
  28.         if(a!=null){
  29.             System.out.print(a.value+" ");
  30.             preOrder(a.left);
  31.             preOrder(a.right);
  32.         }
  33.     }
  34. }
  35.  
  36. class node{
  37.     node left,right;
  38.     int value;
  39.     public void input(int a){
  40.         value=a;
  41.     }
  42.     public static void main(String[] args){
  43.         tree tr=new tree();
  44.         node root=new node();
  45.         int menu=1;
  46.         int r=1;
  47.         int a;
  48.         while(menu!=3){
  49.             System.out.print("1.input\n2.view\n3.exit\n : ");
  50.             menu=tr.in.nextInt();
  51.             if(menu==1){
  52.                 System.out.print("Masukkan Angka : ");
  53.                 a=tr.in.nextInt();
  54.                 if(r==1){
  55.                     root.input(a);
  56.                     r--;
  57.                 }
  58.                 else tr.insert(root,a);
  59.             }
  60.             else if(menu==2) tr.view(root);
  61.             else if(menu==3) System.out.println("Keluar");
  62.             else System.out.println("Salah");
  63.             System.out.println(" ");
  64.         }
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment