DEV Community

Cover image for Data Structure in Java: Binary Search Tree
luthfisauqi17
luthfisauqi17

Posted on • Edited on

Data Structure in Java: Binary Search Tree

public class BinarySearchTree {
    private class Node {
        private int data;
        private Node left, right;

        private Node(int data) {
            this.data = data;
            this.left = this.right = null;
        }
    }

    Node root;

    BinarySearchTree() {
        this.root = null;
    }

    public void insert(int data) {
        this.root = insert(this.root, data);
    }

    private Node insert(Node root, int data) {
        if (root == null) {
            root = new Node(data);
            return root;
        }
        if (data < root.data) root.left = insert(root.left, data);
        else if (data > root.data) root.right = insert(root.right, data);
        return root;
    }

    public void show(String type) {
        switch (type) {
            case "preorder":
                preOrder(this.root);
                break;
            case "inorder":
                inOrder(this.root);
                break;
            case "postorder":
                postOrder(this.root);
                break;
            default:
                System.out.println("Wrong Type (preorder, inorder, postorder)");
        }
    }

    private void preOrder(Node root) {
        if(root != null) {
            System.out.print(root.data + " ");
            inOrder(root.left);
            inOrder(root.right);
        }
    }

    private void inOrder(Node root) {
        if(root != null) {
            inOrder(root.left);
            System.out.print(root.data + " ");
            inOrder(root.right);
        }
    }

    private void postOrder(Node root) {
        if(root != null) {
            inOrder(root.left);
            inOrder(root.right);
            System.out.print(root.data + " ");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Sources and Images:

Top comments (0)