Write a Java program to implement a binary search tree.

class Node {
    int key;
    Node left, right;
 
    public Node(int item) {
        key = item;
        left = right = null;
    }
}
 
class BinarySearchTree {
    // Root of BST
    Node root;
 
    // Constructor
    BinarySearchTree() { 
        root = null; 
    }
 
    // This method mainly calls insertRec()
    void insert(int key) {
       root = insertRec(root, key);
    }
     
    /* A recursive function to insert a new key in BST */
    Node insertRec(Node root, int key) {
 
        /* If the tree is empty, return a new node */
        if (root == null) {
            root = new Node(key);
            return root;
        }
 
        /* Otherwise, recur down the tree */
        if (key < root.key)
            root.left = insertRec(root.left, key);
        else if (key > root.key)
            root.right = insertRec(root.right, key);
 
        /* return the (unchanged) node pointer */
        return root;
    }
 
    // This method mainly calls InorderRec()
    void inorder()  {
       inorderRec(root);
    }
 
    // A utility function to do inorder traversal of BST
    void inorderRec(Node root) {
        if (root != null) {
            inorderRec(root.left);
            System.out.println(root.key);
            inorderRec(root.right);
        }
    }
 
    // Driver Program to test above functions
    public static void main(String[] args) {
        BinarySearchTree tree = new BinarySearchTree();
 
        /* Let us create following BST
              50
           /     \
          30      70
         /  \    /  \
       20   40  60   80 */
        tree.insert(50);
        tree.insert(30);
        tree.insert(20);
        tree.insert(40);
        tree.insert(70);
        tree.insert(60);
        tree.insert(80);
 
        // print inorder traversal of the BST
        tree.inorder();
    }
}
20
30
40
50
60
70
80

This program creates a BinarySearchTree class that has a Node class as an inner class. The Node class has an integer key, and two pointers to its left and right children. The BinarySearchTree class has a root node, and methods for inserting new nodes, and in-order traversal.

The insert() method takes an integer key as input and calls the insertRec() method to insert the key in the tree. The insertRec() method is a recursive function that navigates the tree and places the key in the appropriate position. The inorder() method calls the inorderRec() method which is also a recursive method that traverses the tree in-order and prints the key of each node.

In the main method, it creates an instance of the BinarySearchTree class and inserts several keys into the tree. It then

Leave a Reply

Your email address will not be published. Required fields are marked *