Advertisement
iNoobAvicena

BST

Dec 18th, 2020
843
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.17 KB | None | 0 0
  1. public class Solution {
  2.  
  3.     public static void main(String[] args) {
  4.         Scanner in = new Scanner(System.in);
  5.         BinaryTree cari = new BinaryTree();
  6.         int bt = in.nextInt();
  7.         for (int i = 0; i < bt; i++) {
  8.             cari.add(in.nextInt());
  9.         }
  10.         cari.search(in.nextInt());
  11.     }
  12.  
  13.     public static class Node<Integer> {
  14.         int data;
  15.         Node<Integer> leftChild, rightChild;
  16.  
  17.     public Node(int data) {
  18.             this.data = data;
  19.             leftChild = null;
  20.             rightChild = null;
  21.         }
  22.     }
  23.  
  24.     public static class BinaryTree<Integer> {
  25.  
  26.         public Node<Integer> root;
  27.         static int hitung = 0;
  28.  
  29.         public BinaryTree() {
  30.             Node root;
  31.         }
  32.  
  33.         public BinaryTree(Node root) {
  34.             this.root = root;
  35.         }
  36.  
  37.         public BinaryTree(int data) {
  38.             root = new Node(data);
  39.         }
  40.  
  41.         public boolean isEmpty() {
  42.             return root == null;
  43.         }
  44.         public void add(int data) {
  45.             root = getNode(root, data);
  46.         }
  47.  
  48.         private Node getNode(Node node, int data) {
  49.             if (node == null) {
  50.                 return new Node(data);
  51.             } else if (data < node.data) {
  52.                 node.leftChild = getNode(node.leftChild, data);
  53.             } else if (data > node.data) {
  54.                 node.rightChild = getNode(node.rightChild, data);
  55.             }
  56.             return node;
  57.         }
  58.        
  59.         private int getSearch(Node node, int data) {
  60.             if (node == null) {
  61.                 return -1;
  62.             }
  63.  
  64.             if (data < node.data) {
  65.                 hitung++;
  66.                 int left = getSearch(node.leftChild, data);
  67.                 return left;
  68.             } else if (data > node.data) {
  69.                 hitung++;
  70.                 int right = getSearch(node.rightChild, data);
  71.                 return right;
  72.             } else if (data == node.data) {
  73.                 return hitung;
  74.             }
  75.             return hitung;
  76.         }
  77.  
  78.         public void search(int data) {
  79.             System.out.println(getSearch(root, data));
  80.         }
  81.     }
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement