Creating a Binary Search Tree

In this tutorial we will learn how to Create a Binary Search Tree with examples. The below diagram represents the Binary Search Tree.

Binary Search Tree
Binary Search Tree

How to Create Binary Search Tree

You can Create A Binary Search Tree using its fundamentals which are below:

  • Left subtree nodes always be less than the root node.
  • Right subtree nodes always be greater than the root node.
  • Left and right subtrees also Binary Search Tree without any duplicate nodes.
  • By default there is no duplicate.

Implementation

The process is implemented Recursively. Which is very simple to use. We have an array of elements; each element of array is pushed into the create BST method. In the method first check that the new value is less than or greater than the root value, then assign to its left or right accordingly.


public class BinaryTreeBT {

    static class Node {
        int data;
        Node left;
        Node right;

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

    // creating binary search tree
    public static Node createBST(Node root, int val) {
        if (root == null) {
            root = new Node(val);
            return root;
        }

        if (root.data > val) {
            root.left = createBST(root.left, val);
        } else {
            root.right = createBST(root.right, val);
        }

        return root;
    }

    // traverse the bst inorder
    static void inorder(Node root) {
        if (root == null) {
            return;
        }
        inorder(root.left);
        System.out.print(root.data + " ");
        inorder(root.right);

    }

    public static void main(String[] args) {
        int[] values = {12, 8, 10, 1, 3, 4, 6, 9, 15};
        Node root = null;
        for(int i=0; i<values.length; i++){
            root = createBST(root, values[i]);
        }

        // traverse over the bst
        inorder(root);
        System.out.println("");
       
    }
}

Answer: 1 3 4 6 8 9 10 12 15

Thank you for reaching out this tutorial. You can comment in the comments section below for any doubt or query. Want to learn more about BST?

Thank You FlutterTPoint
Thank You FlutterTPoint

Don’t miss new tips!

We don’t spam! Read our [link]privacy policy[/link] for more info.

Leave a Comment

Scroll to Top