/Binary Search Tree

Binary Search Tree

Node class

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

    public int getData() {
        return data;
    }

    public void setData(int data) {
        this.data = data;
    }

    public Node getLeft() {
        return left;
    }

    public void setLeft(Node left) {
        this.left = left;
    }

    public Node getRight() {
        return right;
    }

    public void setRight(Node right) {
        this.right = right;
    }

    @Override
    public String toString() {
        return "Node{" + "data=" + data + ", left=" + left + ", right=" + right + '}';
    }
}

Binary Search Tree Class

public class BinarySearchTree {

    private Node root;

    public BinarySearchTree() {
        root = null;
    }

    public Node getRoot() {
        return root;
    }

    public void insert(int data) {
        Node temp = getRoot();
        if (temp == null) {
            temp = new Node(data);
            root = temp;
        } else {
            insert(temp, data);
        }
    }

    private Node insert(Node root, int data) {
        if (root == null) {
            return new Node(data);
        } else {
            if (root.getData() > data) {
                root.setLeft(insert(root.getLeft(), data));
            } else if (root.getData() < data) {
                root.setRight(insert(root.getRight(), data));
            }
        }
        return root;
    }

    public void preorder(Node root) {
        if (root != null) {
            System.out.print(root.getData() + " ");
            preorder(root.getLeft());
            preorder(root.getRight());
        }
    }

    public void postorder(Node root) {
        if (root != null) {
            postorder(root.getLeft());
            postorder(root.getRight());
            System.out.print(root.getData() + " ");
        }
    }

    public void inorder(Node root) {
        if (root != null) {
            inorder(root.getLeft());
            System.out.print(root.getData() + " ");
            inorder(root.getRight());
        }
    }
}

Binary Search Tree Example Class

public class BinarySearchTreeExample {

    public static void main(String args[]) {
        BinarySearchTree binarysearchtree = new BinarySearchTree();
        binarysearchtree.insert(5);
        binarysearchtree.insert(3);
        binarysearchtree.insert(7);
        binarysearchtree.insert(9);
        binarysearchtree.insert(4);
        binarysearchtree.insert(2);
        
        binarysearchtree.preorder(binarysearchtree.getRoot());
    }
}