C++ Program to Implement Binary Search Tree

The below program demonstrates all the major operations on a binary search tree: creation, searching, insertion and deletion.

C++
// C++ Program to implement binary search tree

#include <iostream>
using namespace std;

// Node structure for a Binary Search Tree
struct Node {
    int data;
    Node* left;
    Node* right;
};

// Function to create a new Node
Node* createNode(int data)
{
    Node* newNode = new Node();
    newNode->data = data;
    newNode->left = newNode->right = nullptr;
    return newNode;
}

// Function to insert a node in the BST
Node* insertNode(Node* root, int data)
{
    if (root == nullptr) { // If the tree is empty, return a
                           // new node
        return createNode(data);
    }

    // Otherwise, recur down the tree
    if (data < root->data) {
        root->left = insertNode(root->left, data);
    }
    else if (data > root->data) {
        root->right = insertNode(root->right, data);
    }

    // return the (unchanged) node pointer
    return root;
}

// Function to do inorder traversal of BST
void inorderTraversal(Node* root)
{
    if (root != nullptr) {
        inorderTraversal(root->left);
        cout << root->data << " ";
        inorderTraversal(root->right);
    }
}

// Function to search a given key in a given BST
Node* searchNode(Node* root, int key)
{
    // Base Cases: root is null or key is present at root
    if (root == nullptr || root->data == key) {
        return root;
    }

    // Key is greater than root's key
    if (root->data < key) {
        return searchNode(root->right, key);
    }

    // Key is smaller than root's key
    return searchNode(root->left, key);
}

// Function to find the inorder successor
Node* minValueNode(Node* node)
{
    Node* current = node;
    // loop down to find the leftmost leaf
    while (current && current->left != nullptr) {
        current = current->left;
    }
    return current;
}

// Function to delete a node
Node* deleteNode(Node* root, int data)
{
    if (root == nullptr)
        return root;

    // If the data to be deleted is smaller than the root's
    // data, then it lies in the left subtree
    if (data < root->data) {
        root->left = deleteNode(root->left, data);
    }
    // If the data to be deleted is greater than the root's
    // data, then it lies in the right subtree
    else if (data > root->data) {
        root->right = deleteNode(root->right, data);
    }
    // if data is same as root's data, then This is the node
    // to be deleted
    else {
        // node with only one child or no child
        if (root->left == nullptr) {
            Node* temp = root->right;
            delete root;
            return temp;
        }
        else if (root->right == nullptr) {
            Node* temp = root->left;
            delete root;
            return temp;
        }

        // node with two children: Get the inorder successor
        // (smallest in the right subtree)
        Node* temp = minValueNode(root->right);

        // Copy the inorder successor's content to this node
        root->data = temp->data;

        // Delete the inorder successor
        root->right = deleteNode(root->right, temp->data);
    }
    return root;
}

// Main function to demonstrate the operations of BST
int main()
{

    Node* root = nullptr;
    // create a BST
    root = insertNode(root, 50);
    root = insertNode(root, 30);
    root = insertNode(root, 20);
    root = insertNode(root, 40);
    root = insertNode(root, 70);
    root = insertNode(root, 60);
    root = insertNode(root, 80);

    // Print the inorder traversal of a BST
    cout << "Inorder traversal of the given Binary Search "
            "Tree is: ";
    inorderTraversal(root);
    cout << endl;

    // delete a node in BST
    root = deleteNode(root, 20);
    cout << "After deletion of 20: ";
    inorderTraversal(root);
    cout << endl;

    // Insert a node in BST
    root = insertNode(root, 25);
    cout << "After insertion of 25: ";
    inorderTraversal(root);
    cout << endl;

    // Search a key in BST
    Node* found = searchNode(root, 25);

    // check if the key is found or not
    if (found != nullptr) {
        cout << "Node 25 found in the BST." << endl;
    }
    else {
        cout << "Node 25 not found in the BST." << endl;
    }

    return 0;
}

Output
Inorder traversal of the given Binary Search Tree is: 20 30 40 50 60 70 80 
After deletion of 20: 30 40 50 60 70 80 
After insertion of 25: 25 30 40 50 60 70 80 
Node 25 found in the BST.

Time Complexity:
Auxilliary Space:

The average time complexity for all three operations on BST is O (log n). In the worst case (Skewed BST) the time complexity can become O (n). n = number of nodes.The Space complexity for all three operations done on BST is O (1). This means no extra space or memory is required to perform these operations on a BST.

Binary Search Tree in C++

A Binary Search Tree (BST) is a type of binary tree in which the data is organized and stored in a sorted order. Unlike, a binary tree that doesn’t follow a specific order for node placement, in a binary search tree all the elements on the left side of a node are smaller than the node itself, and elements on the right side of a node are greater.

In this article, we will learn more about the binary search tree, operations performed on BST, and implementation of BST, as well as the advantages, disadvantages, and applications of binary search tree in C++.

Similar Reads

What is a Binary Search Tree (BST)?

A Binary Search Tree (BST) is a binary tree in which every node contains only smaller values in its left subtree and only larger values in its right subtree. This property is called the BST property and every binary search tree follows this property as it allows efficient insertion, deletion, and search operations in a tree....

Binary Search Tree Representation in C++

In BST, every value on the left subtree < parent node < right subtree value....

Basic Operations on Binary Search Tree

The following are the basics operations performed on a binary search tree:...

C++ Program to Implement Binary Search Tree

The below program demonstrates all the major operations on a binary search tree: creation, searching, insertion and deletion....

Applications of Binary Search Tree

Following are the applications of binary search tree:...

Advantages of Binary Search Tree

Because of the unique properties of BST, it provides an efficient way to search an element having O(log n) time complexity. The In-Order Traversal of BST is always in a sorted order. So, it becomes easier to retrieve elements in sorted order in a BST.It can adapt to various applications by defining a custom node structure.Balanced Binary search tree have logarithmic height that ensures efficient operations.It stores only the key values, that makes them space-efficient....

Disadvantages of Binary Search Tree

The performance of BST depends upon its balance. Skewed BST is the worst-case scenario where the search complexity becomes O(n), just like any other tree.Although operations like insertion and deletion are easy in BST, maintaining the balance of the tree is hard.If the tree is made by using a sorted list, then the creation can lead to a highly unbalanced BST which degrades its performance. One solution is to balance the tree after every insertion.Binary search tree become less efficient for very large datasets...

Frequently Asked Questions on Binary Search Tree

What is Binary Search Tree (BST)?...