Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Solution {
- public static void main(String[] args) {
- Scanner in = new Scanner(System.in);
- BinaryTree cari = new BinaryTree();
- int bt = in.nextInt();
- for (int i = 0; i < bt; i++) {
- cari.add(in.nextInt());
- }
- cari.search(in.nextInt());
- }
- public static class Node<Integer> {
- int data;
- Node<Integer> leftChild, rightChild;
- public Node(int data) {
- this.data = data;
- leftChild = null;
- rightChild = null;
- }
- }
- public static class BinaryTree<Integer> {
- public Node<Integer> root;
- static int hitung = 0;
- public BinaryTree() {
- Node root;
- }
- public BinaryTree(Node root) {
- this.root = root;
- }
- public BinaryTree(int data) {
- root = new Node(data);
- }
- public boolean isEmpty() {
- return root == null;
- }
- public void add(int data) {
- root = getNode(root, data);
- }
- private Node getNode(Node node, int data) {
- if (node == null) {
- return new Node(data);
- } else if (data < node.data) {
- node.leftChild = getNode(node.leftChild, data);
- } else if (data > node.data) {
- node.rightChild = getNode(node.rightChild, data);
- }
- return node;
- }
- private int getSearch(Node node, int data) {
- if (node == null) {
- return -1;
- }
- if (data < node.data) {
- hitung++;
- int left = getSearch(node.leftChild, data);
- return left;
- } else if (data > node.data) {
- hitung++;
- int right = getSearch(node.rightChild, data);
- return right;
- } else if (data == node.data) {
- return hitung;
- }
- return hitung;
- }
- public void search(int data) {
- System.out.println(getSearch(root, data));
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement