Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Search and Insertion in Binary Search Tree

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

What is Binary Search Tree?

A Binary Search Tree is a special type of binary tree data structure which has the following properties:  

  • The left subtree of a node contains only nodes with keys lesser than the node’s key.
  • The right subtree of a node contains only nodes with keys greater than the node’s key.
  • The left and right subtree each must also be a binary search tree.

There must be no duplicate nodes.

Example of BST

Example of BST

The above properties of the Binary Search Tree provide an ordering among keys so that the operations like search, minimum and maximum can be done fast. If there is no order, then we may have to compare every key to search for a given key.

How to search for a key in a given Binary Tree?

For searching a value, if we had a sorted array we could have performed a binary search.

Search operations in binary search trees will be very similar to that. Let’s say we want to search for the number X

  • We start at the root, and then we compare the value to be searched with the value of the root, 
    • If it’s equal we are done with the search if it’s smaller we know that we need to go to the left subtree because in a binary search tree all the elements in the left subtree are smaller and all the elements in the right subtree are larger. 
    • Searching an element in the binary search tree is basically this traversal, at each step we go either left or right and at each step we discard one of the sub-trees. 

If the tree is balanced, (we call a tree balanced if for all nodes the difference between the heights of left and right subtrees is not greater than one) we start with a search space of ‘n’ nodes and as we discard one of the sub-trees, we discard ‘n/2’ nodes so our search space gets reduced to ‘n/2’. In the next step, we reduce the search space to ‘n/4’ and we repeat until we find the element or our search space is reduced to only one node. The search here is also a binary search hence the name; Binary Search Tree.

Illustration of searching in BST:

See the illustration below for a better understanding:

Consider the graph shown below and the key = 6.

BST example

BST example

  • Initially compare the key with the root i.e., 8. As 6 is less than 8, search in the left subtree of 8.
  • Now compare the key with 3. As key is greater than 3, search next in the right subtree of 3.
  • Now compare the key with 6. The value of the key is 6. So we have found the key

Program to implement search in BST:

C++




// C function to search a given key in a given BST
struct node* search(struct node* root, int key)
{
    // Base Cases: root is null or key is present at root
    if (root == NULL || root->key == key)
        return root;
 
    // Key is greater than root's key
    if (root->key < key)
        return search(root->right, key);
 
    // Key is smaller than root's key
    return search(root->left, key);
}


Java




// A utility function to search a given key in BST
public Node search(Node root, int key)
{
    // Base Cases: root is null or key is present at root
    if (root == null || root.key == key)
        return root;
 
    // Key is greater than root's key
    if (root.key < key)
        return search(root.right, key);
 
    // Key is smaller than root's key
    return search(root.left, key);
}


Python




# A utility function to search a given key in BST
def search(root, key):
 
    # Base Cases: root is null or key is present at root
    if root is None or root.val == key:
        return root
 
    # Key is greater than root's key
    if root.val < key:
        return search(root.right, key)
 
    # Key is smaller than root's key
    return search(root.left, key)
 
# This code is contributed by Bhavya Jain


C#




// A utility function to search
// a given key in BST
public Node search(Node root, int key)
{
    // Base Cases: root is null
    // or key is present at root
    if (root == null || root.key == key)
        return root;
 
    // Key is greater than root's key
    if (root.key < key)
        return search(root.right, key);
 
    // Key is smaller than root's key
    return search(root.left, key);
}
 
// This code is contributed by gauravrajput1


Javascript




<script>
 
// A utility function to search
// a given key in BST
function search(root, key)
{
    // Base Cases: root is null
    // or key is present at root
    if (root == null ||
        root.key == key)
        return root;
 
   // Key is greater than root's key
    if (root.key < key)
       return search(root.right, key);
 
    // Key is smaller than root's key
    return search(root.left, key);
}
 
// This code is contributed by rrrtnx.
</script>


Time complexity: O(h), where h is the height of the BST.
Space complexity: O(h), where h is the height of the BST. This is because the maximum amount of space needed to store the recursion stack would be h.

How to insert a value in BST?

The insertion logic into BST is similar to its searching operation. A new value is always inserted at the leaf node of the BST.

  • Compare the value with the root of the BST.
    • If the value to be inserted is less than the root, move to the left subtree. 
    • Otherwise, if the value is greater than the root, move to the right subtree.
  • Continue this process, until we hit a leaf node.
  • If the value is less than the leaf, create a left child of the leaf and insert the value.
  • Otherwise, if the value is greater than the leaf, create a right child of the leaf and insert the value in the right child.

Illustration of Insertion in BST:

Check the below illustration for a better understanding

Consider the following BST and the value = 40 to be added.

Example of BST

Example of BST

  • Initially, 40 is less than 100. So move to the left subtree.
  • Now, 40 is greater than 20. So move to the right subtree.
  • Now we reach the leaf node 30. As 40 is greater than 30, create right child of 30 and insert the value 40.
Inserted 40 in the above example

Inserted 40 in the above example

The final BST after insertion will look like the above image.

Program to implement insertion in BST:

C




// C program to demonstrate insert operation
// in binary search tree.
 
#include <stdio.h>
#include <stdlib.h>
 
struct node {
    int key;
    struct node *left, *right;
};
 
// A utility function to create a new BST node
struct node* newNode(int item)
{
    struct node* temp
        = (struct node*)malloc(sizeof(struct node));
    temp->key = item;
    temp->left = temp->right = NULL;
    return temp;
}
 
// A utility function to do inorder traversal of BST
void inorder(struct node* root)
{
    if (root != NULL) {
        inorder(root->left);
        printf("%d ", root->key);
        inorder(root->right);
    }
}
 
// A utility function to insert
// a new node with given key in BST
struct node* insert(struct node* node, int key)
{
    // If the tree is empty, return a new node
    if (node == NULL)
        return newNode(key);
 
    // Otherwise, recur down the tree
    if (key < node->key)
        node->left = insert(node->left, key);
    else if (key > node->key)
        node->right = insert(node->right, key);
 
    // Return the (unchanged) node pointer
    return node;
}
 
// Driver Code
int main()
{
    struct node* root = NULL;
    root = insert(root, 50);
    insert(root, 30);
    insert(root, 20);
    insert(root, 40);
    insert(root, 70);
    insert(root, 60);
    insert(root, 80);
 
    // Print inoder traversal of the BST
    inorder(root);
 
    return 0;
}


C++




// C++ program to demonstrate insertion
// in a BST recursively
 
#include <bits/stdc++.h>
using namespace std;
 
class BST {
    int data;
    BST *left, *right;
 
public:
    // Default constructor.
    BST();
 
    // Parameterized constructor.
    BST(int);
 
    // Insert function.
    BST* Insert(BST*, int);
 
    // Inorder traversal.
    void Inorder(BST*);
};
 
// Default Constructor definition.
BST ::BST()
    : data(0)
    , left(NULL)
    , right(NULL)
{
}
 
// Parameterized Constructor definition.
BST ::BST(int value)
{
    data = value;
    left = right = NULL;
}
 
// Insert function definition.
BST* BST ::Insert(BST* root, int value)
{
    if (!root) {
        // Insert the first node, if root is NULL.
        return new BST(value);
    }
 
    // Insert right node data, if the 'value'
    // to be inserted is greater than 'root' node data.
    if (value > root->data) {
        root->right = Insert(root->right, value);
    }
   
    // Insert left node data, if the 'value'
    // to be inserted is smaller than 'root' node data.
    else if (value < root->data) {
        root->left = Insert(root->left, value);
    }
 
    // Return 'root' node, after insertion.
    return root;
}
 
// Inorder traversal function.
// This gives data in sorted order.
void BST ::Inorder(BST* root)
{
    if (!root) {
        return;
    }
    Inorder(root->left);
    cout << root->data << " ";
    Inorder(root->right);
}
 
// Driver code
int main()
{
    BST b, *root = NULL;
    root = b.Insert(root, 50);
    b.Insert(root, 30);
    b.Insert(root, 20);
    b.Insert(root, 40);
    b.Insert(root, 70);
    b.Insert(root, 60);
    b.Insert(root, 80);
 
    b.Inorder(root);
    return 0;
}
 
// This code is contributed by pkthapa


Java




// Java program to demonstrate insert operation
// in binary search tree
 
import java.io.*;
 
public class BinarySearchTree {
 
    // Class containing left and right child of
    // current node and key value
    class Node {
        int key;
        Node left, right;
 
        public Node(int item)
        {
            key = item;
            left = right = null;
        }
    }
 
    // Root of BST
    Node root;
 
    // Constructor
    BinarySearchTree() { root = null; }
 
    BinarySearchTree(int value) { root = new Node(value); }
 
    // 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.print(root.key + " ");
            inorderRec(root.right);
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        BinarySearchTree tree = new BinarySearchTree();
        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();
    }
}
// This code is contributed by Ankur Narain Verma


Python3




# Python program to demonstrate
# insert operation in binary search tree
 
 
# A utility class that represents
# an individual node in a BST
class Node:
    def __init__(self, key):
        self.left = None
        self.right = None
        self.val = key
 
 
# A utility function to insert
# a new node with the given key
def insert(root, key):
    if root is None:
        return Node(key)
    else:
        if root.val == key:
            return root
        elif root.val < key:
            root.right = insert(root.right, key)
        else:
            root.left = insert(root.left, key)
    return root
 
 
# A utility function to do inorder tree traversal
def inorder(root):
    if root:
        inorder(root.left)
        print(root.val, end=" ")
        inorder(root.right)
 
 
# Driver code
if __name__ == '__main__':
    r = Node(50)
    r = insert(r, 30)
    r = insert(r, 20)
    r = insert(r, 40)
    r = insert(r, 70)
    r = insert(r, 60)
    r = insert(r, 80)
     
    # Print inoder traversal of the BST
    inorder(r)


C#




// C# program to demonstrate insert operation
// in binary search tree
 
using System;
 
class BinarySearchTree {
 
    // Class containing left and
    // right child of current node
    // and key value
    public class Node {
        public int key;
        public Node left, right;
 
        public Node(int item)
        {
            key = item;
            left = right = null;
        }
    }
 
    // Root of BST
    Node root;
 
    // Constructor
    BinarySearchTree() { root = null; }
 
    BinarySearchTree(int value) { root = new Node(value); }
 
    // 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);
            Console.Write(root.key + " ");
            inorderRec(root.right);
        }
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        BinarySearchTree tree = new BinarySearchTree();
        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();
    }
}
 
// This code is contributed by aashish1995


Javascript




<script>
// javascript program to demonstrate
// insert operation in binary
// search tree
    /*
     * Class containing left and right child of current node and key value
     */
    class Node {
     
constructor(item) {
            this.key = item;
            this.left = this.right = null;
        }
    }
 
    // Root of BST
    var root = null;
 
    // This method mainly calls insertRec()
    function insert(key) {
        root = insertRec(root, key);
    }
 
    /*
     * A recursive function to insert a new key in BST
     */
    function insertRec(root , 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()
    function inorder() {
        inorderRec(root);
    }
 
    // A utility function to
    // do inorder traversal of BST
    function inorderRec(root)
    {
        if (root != null) {
            inorderRec(root.left);
            document.write(root.key+"<br/>");
            inorderRec(root.right);
        }
    }
 
// Driver Code
 
        /* Let us create following BST
              50
           /     \
          30      70
         /  \    /  \
       20   40  60   80 */
        insert(50);
        insert(30);
        insert(20);
        insert(40);
        insert(70);
        insert(60);
        insert(80);
 
        // print inorder traversal of the BST
        inorder();
 
// This code is contributed by Rajput-Ji
</script>


Output

20 30 40 50 60 70 80 

Time Complexity: 

  • O(h) where h is the height of the Binary Search Tree. In the worst case, we may have to travel from the root to the deepest leaf node.
  • The height of a skewed tree may become n and the time complexity of the search and insert operation may become O(n). 

Auxiliary Space: O(1)

Below is another Implementation using iterative approach:

C++




// C++ Code to insert node and to print inorder traversal
// using iteration
 
#include <bits/stdc++.h>
using namespace std;
 
// BST Node
class Node {
public:
    int val;
    Node* left;
    Node* right;
    Node(int val)
        : val(val)
        , left(NULL)
        , right(NULL)
    {
    }
};
 
// Utility function to insert node in BST
void insert(Node*& root, int key)
{
    Node* node = new Node(key);
    if (!root) {
        root = node;
        return;
    }
    Node* prev = NULL;
    Node* temp = root;
    while (temp) {
        if (temp->val > key) {
            prev = temp;
            temp = temp->left;
        }
        else if (temp->val < key) {
            prev = temp;
            temp = temp->right;
        }
    }
    if (prev->val > key)
        prev->left = node;
    else
        prev->right = node;
}
 
// Utility function to print inorder traversal
void inorder(Node* root)
{
    Node* temp = root;
    stack<Node*> st;
    while (temp != NULL || !st.empty()) {
        if (temp != NULL) {
            st.push(temp);
            temp = temp->left;
        }
        else {
            temp = st.top();
            st.pop();
            cout << temp->val << " ";
            temp = temp->right;
        }
    }
}
 
// Driver code
int main()
{
    Node* root = NULL;
    insert(root, 30);
    insert(root, 50);
    insert(root, 15);
    insert(root, 20);
    insert(root, 10);
    insert(root, 40);
    insert(root, 60);
 
    inorder(root);
 
    return 0;
}
 
// This code is contributed by Tapesh(tapeshdua420)


Java




import java.io.*;
import java.util.*;
 
class GFG {
    public static void main(String[] args)
    {
        BST tree = new BST();
        tree.insert(30);
        tree.insert(50);
        tree.insert(15);
        tree.insert(20);
        tree.insert(10);
        tree.insert(40);
        tree.insert(60);
        tree.inorder();
    }
}
 
class Node {
    Node left;
    int val;
    Node right;
    Node(int val) { this.val = val; }
}
 
class BST {
    Node root;
 
    public void insert(int key)
    {
        Node node = new Node(key);
        if (root == null) {
            root = node;
            return;
        }
        Node prev = null;
        Node temp = root;
        while (temp != null) {
            if (temp.val > key) {
                prev = temp;
                temp = temp.left;
            }
            else if (temp.val < key) {
                prev = temp;
                temp = temp.right;
            }
        }
        if (prev.val > key)
            prev.left = node;
        else
            prev.right = node;
    }
 
    public void inorder()
    {
        Node temp = root;
        Stack<Node> stack = new Stack<>();
        while (temp != null || !stack.isEmpty()) {
            if (temp != null) {
                stack.add(temp);
                temp = temp.left;
            }
            else {
                temp = stack.pop();
                System.out.print(temp.val + " ");
                temp = temp.right;
            }
        }
    }
}


Python3




class GFG:
    @staticmethod
    def main(args):
        tree = BST()
        tree.insert(30)
        tree.insert(50)
        tree.insert(15)
        tree.insert(20)
        tree.insert(10)
        tree.insert(40)
        tree.insert(60)
        tree.inorder()
 
 
class Node:
    left = None
    val = 0
    right = None
 
    def __init__(self, val):
        self.val = val
 
 
class BST:
    root = None
 
    def insert(self, key):
        node = Node(key)
        if (self.root == None):
            self.root = node
            return
        prev = None
        temp = self.root
        while (temp != None):
            if (temp.val > key):
                prev = temp
                temp = temp.left
            elif(temp.val < key):
                prev = temp
                temp = temp.right
        if (prev.val > key):
            prev.left = node
        else:
            prev.right = node
 
    def inorder(self):
        temp = self.root
        stack = []
        while (temp != None or not (len(stack) == 0)):
            if (temp != None):
                stack.append(temp)
                temp = temp.left
            else:
                temp = stack.pop()
                print(str(temp.val) + " ", end="")
                temp = temp.right
 
 
if __name__ == "__main__":
    GFG.main([])
 
    # This code is contributed by rastogik346.


C#




using System;
using System.Collections.Generic;
 
public class GFG {
    public static void Main(String[] args)
    {
        BST tree = new BST();
        tree.insert(30);
        tree.insert(50);
        tree.insert(15);
        tree.insert(20);
        tree.insert(10);
        tree.insert(40);
        tree.insert(60);
        tree.inorder();
    }
}
 
public class Node {
    public Node left;
    public int val;
    public Node right;
 
    public Node(int val) { this.val = val; }
}
 
public class BST {
    public Node root;
 
    public void insert(int key)
    {
        Node node = new Node(key);
        if (root == null) {
            root = node;
            return;
        }
        Node prev = null;
        Node temp = root;
        while (temp != null) {
            if (temp.val > key) {
                prev = temp;
                temp = temp.left;
            }
            else if (temp.val < key) {
                prev = temp;
                temp = temp.right;
            }
        }
        if (prev.val > key)
            prev.left = node;
        else
            prev.right = node;
    }
 
    public void inorder()
    {
        Node temp = root;
        Stack<Node> stack = new Stack<Node>();
        while (temp != null || stack.Count != 0) {
            if (temp != null) {
                stack.Push(temp);
                temp = temp.left;
            }
            else {
                temp = stack.Pop();
                Console.Write(temp.val + " ");
                temp = temp.right;
            }
        }
    }
}
 
// This code is contributed by Rajput-Ji


Javascript




// JS Code to insert node and to print inorder traversal
// using iteration
 
// BST Node
class Node {
    constructor(val) {
        this.val = val;
        this.right = null
        this.left = null
    }
}
// Utility function to insert node in BST
function insert(root, key) {
    let node = new Node(key);
    if (!root) {
        root = node;
        return;
    }
    let prev = null;
    let temp = root;
    while (temp) {
        if (temp.val > key) {
            prev = temp;
            temp = temp.left;
        }
        else if (temp.val < key) {
            prev = temp;
            temp = temp.right;
        }
    }
    if (prev.val > key)
        prev.left = node;
    else
        prev.right = node;
}
// Utility function to print inorder traversal
function inorder(root)
{
    let temp = root;
    let st=[];
    while (temp != null || st.length!=0) {
        if (temp != null) {
            st.unshift(temp);
            temp = temp.left;
        }
        else {
            temp = st[0];
            st.shift();
            if(temp.val){
                console.log(temp.val);
            }
            temp = temp.right;
        }
    }
}
 
 
// Driver code
let root = new Node(null);
insert(root, 30);
insert(root, 50);
insert(root, 15);
insert(root, 20);
insert(root, 10);
insert(root, 40);
insert(root, 60);
 
inorder(root);
 
// This code is contributed by adityamaharshi21


Output

10 15 20 30 40 50 60 

Time Complexity: O(h) where h is the height of the BST (because we are not considering the inorder traversal for complexity of insertion.
Auxiliary Space: O(h)

 

Some Interesting Facts: 

Related Links: 


My Personal Notes arrow_drop_up
Last Updated : 15 May, 2023
Like Article
Save Article
Similar Reads
Related Tutorials