Two centers in Dehradun — Kanwali Road & Premnagar

Binary Search Tree Using C – Practical Coding Exercises with Solutions

Pivot Edu Unit Practice & Tutorials

Introduction to Binary Search Tree (BST)

A Binary Search Tree (BST) is a special type of binary tree in which each node contains a data value and has at most two children. The left subtree contains values smaller than the root node, while the right subtree contains values greater than the root node.

Properties of a Binary Search Tree

  • Values smaller than the root are inserted into the left subtree.
  • Values greater than the root are inserted into the right subtree.
  • Each node can have a maximum of two children.
  • Duplicate values are not inserted in our practice programs.
  • Inorder traversal displays BST elements in ascending order.

Basic Structure of a BST Node in C

#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node *left;
    struct Node *right;
};

We use a structure to represent each node. The data member stores the integer value, while left and right pointers connect the node to its child nodes.

Exercise 1: Create a Binary Search Tree and Insert Elements

Problem: Write a C program to create a Binary Search Tree by inserting the following elements: 50, 30, 70, 20, 40, 60 and 80. Display the tree using inorder traversal.

Step-by-Step Solution

  1. Create a structure named Node containing data, left and right pointers.
  2. Write an insert() function to create and insert new nodes.
  3. If the tree is empty, create the root node.
  4. If the new value is smaller than the current node, insert it into the left subtree.
  5. If the new value is greater, insert it into the right subtree.
  6. Use inorder traversal to display the elements.

C Program

#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node *left, *right;
};

struct Node* insert(struct Node* root, int value) {
    if (root == NULL) {
        struct Node* newNode = malloc(sizeof(struct Node));
        newNode->data = value;
        newNode->left = NULL;
        newNode->right = NULL;
        return newNode;
    }

    if (value < root->data)
        root->left = insert(root->left, value);
    else if (value > root->data)
        root->right = insert(root->right, value);

    return root;
}

void inorder(struct Node* root) {
    if (root != NULL) {
        inorder(root->left);
        printf("%d ", root->data);
        inorder(root->right);
    }
}

int main() {
    struct Node* root = NULL;
    int arr[] = {50, 30, 70, 20, 40, 60, 80};
    int n = 7;

    for (int i = 0; i < n; i++)
        root = insert(root, arr[i]);

    printf("Inorder Traversal: ");
    inorder(root);
    return 0;
}

Expected Output

Inorder Traversal: 20 30 40 50 60 70 80

Understanding the BST Structure

          50
        /    \
       30     70
      /  \   /  \
     20  40 60  80

Concept learned: Creating nodes dynamically, recursive insertion and inorder traversal.

Exercise 2: Search for an Element in a Binary Search Tree

Problem: Create a BST using the values 45, 25, 65, 15, 35, 55 and 75. Write a C program to search for a number entered by the user and display whether the element exists in the tree.

Step-by-Step Solution

  1. Create the BST using the insertion function from Exercise 1.
  2. Accept a search value from the user.
  3. Compare the search value with the current node's data.
  4. If both values are equal, the element is found.
  5. If the search value is smaller, continue searching in the left subtree.
  6. Otherwise, search in the right subtree.
  7. If the current node becomes NULL, the element does not exist.

C Program

#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node *left, *right;
};

struct Node* insert(struct Node* root, int value) {
    if (root == NULL) {
        struct Node* temp = malloc(sizeof(struct Node));
        temp->data = value;
        temp->left = temp->right = NULL;
        return temp;
    }

    if (value < root->data)
        root->left = insert(root->left, value);
    else if (value > root->data)
        root->right = insert(root->right, value);

    return root;
}

int search(struct Node* root, int key) {
    if (root == NULL)
        return 0;

    if (root->data == key)
        return 1;

    if (key < root->data)
        return search(root->left, key);

    return search(root->right, key);
}

int main() {
    struct Node* root = NULL;
    int arr[] = {45, 25, 65, 15, 35, 55, 75};
    int key;

    for (int i = 0; i < 7; i++)
        root = insert(root, arr[i]);

    printf("Enter number to search: ");
    scanf("%d", &key);

    if (search(root, key))
        printf("Element Found");
    else
        printf("Element Not Found");

    return 0;
}

Sample Output

Enter number to search: 55
Element Found

Concept learned: Recursive searching and comparison-based navigation in a BST.

Exercise 3: Display Preorder, Inorder and Postorder Traversals

Problem: Construct a BST using the elements 40, 20, 60, 10, 30, 50 and 70. Write a C program to display all three tree traversal techniques.

Step-by-Step Solution

  1. Construct the BST using the insertion function.
  2. For preorder traversal, display the root, visit the left subtree and then the right subtree.
  3. For inorder traversal, visit the left subtree, display the root and then visit the right subtree.
  4. For postorder traversal, visit the left subtree, visit the right subtree and finally display the root.

C Program

#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node *left, *right;
};

struct Node* insert(struct Node* root, int value) {
    if (root == NULL) {
        struct Node* temp = malloc(sizeof(struct Node));
        temp->data = value;
        temp->left = temp->right = NULL;
        return temp;
    }

    if (value < root->data)
        root->left = insert(root->left, value);
    else if (value > root->data)
        root->right = insert(root->right, value);

    return root;
}

void preorder(struct Node* root) {
    if (root != NULL) {
        printf("%d ", root->data);
        preorder(root->left);
        preorder(root->right);
    }
}

void inorder(struct Node* root) {
    if (root != NULL) {
        inorder(root->left);
        printf("%d ", root->data);
        inorder(root->right);
    }
}

void postorder(struct Node* root) {
    if (root != NULL) {
        postorder(root->left);
        postorder(root->right);
        printf("%d ", root->data);
    }
}

int main() {
    struct Node* root = NULL;
    int arr[] = {40, 20, 60, 10, 30, 50, 70};

    for (int i = 0; i < 7; i++)
        root = insert(root, arr[i]);

    printf("Preorder: ");
    preorder(root);

    printf("\nInorder: ");
    inorder(root);

    printf("\nPostorder: ");
    postorder(root);

    return 0;
}

Expected Output

Preorder: 40 20 10 30 60 50 70
Inorder: 10 20 30 40 50 60 70
Postorder: 10 30 20 50 70 60 40

Concept learned: Understanding the three fundamental recursive tree traversal algorithms.

Exercise 4: Find the Minimum and Maximum Element in a BST

Problem: Create a BST using the values 50, 30, 70, 20, 40, 60 and 90. Write a C program to find and display the smallest and largest elements in the tree.

Step-by-Step Solution

  1. Insert all given elements into the BST.
  2. To find the minimum value, start from the root and keep moving to the left child.
  3. When the left child becomes NULL, the current node contains the minimum value.
  4. To find the maximum value, start from the root and keep moving to the right child.
  5. When the right child becomes NULL, the current node contains the maximum value.

C Program

#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node *left, *right;
};

struct Node* insert(struct Node* root, int value) {
    if (root == NULL) {
        struct Node* temp = malloc(sizeof(struct Node));
        temp->data = value;
        temp->left = temp->right = NULL;
        return temp;
    }

    if (value < root->data)
        root->left = insert(root->left, value);
    else if (value > root->data)
        root->right = insert(root->right, value);

    return root;
}

struct Node* findMin(struct Node* root) {
    if (root == NULL)
        return NULL;

    while (root->left != NULL)
        root = root->left;

    return root;
}

struct Node* findMax(struct Node* root) {
    if (root == NULL)
        return NULL;

    while (root->right != NULL)
        root = root->right;

    return root;
}

int main() {
    struct Node* root = NULL;
    int arr[] = {50, 30, 70, 20, 40, 60, 90};

    for (int i = 0; i < 7; i++)
        root = insert(root, arr[i]);

    printf("Minimum Element: %d\n", findMin(root)->data);
    printf("Maximum Element: %d\n", findMax(root)->data);

    return 0;
}

Expected Output

Minimum Element: 20
Maximum Element: 90

Concept learned: Finding boundary values in a BST using iterative traversal.

Exercise 5: Delete a Node from a Binary Search Tree

Problem: Create a BST using the values 50, 30, 70, 20, 40, 60 and 80. Write a C program to delete a given element from the BST and display the updated tree using inorder traversal.

Understanding the Three Deletion Cases

  • Case 1 – Leaf Node: If the node has no children, simply remove it.
  • Case 2 – One Child: Replace the node with its only child.
  • Case 3 – Two Children: Replace the node's value with its inorder successor (smallest value in the right subtree), then delete that successor.

Step-by-Step Solution

  1. Search for the node that needs to be deleted.
  2. If the node has no left child, return its right child after freeing the node.
  3. If the node has no right child, return its left child after freeing the node.
  4. If the node has two children, find the minimum node in its right subtree.
  5. Copy the inorder successor's value into the node.
  6. Delete the original successor node from the right subtree.
  7. Display the updated tree using inorder traversal.

C Program

#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node *left, *right;
};

struct Node* insert(struct Node* root, int value) {
    if (root == NULL) {
        struct Node* temp = malloc(sizeof(struct Node));
        temp->data = value;
        temp->left = temp->right = NULL;
        return temp;
    }

    if (value < root->data)
        root->left = insert(root->left, value);
    else if (value > root->data)
        root->right = insert(root->right, value);

    return root;
}

struct Node* findMin(struct Node* root) {
    while (root != NULL && root->left != NULL)
        root = root->left;
    return root;
}

struct Node* deleteNode(struct Node* root, int key) {
    if (root == NULL)
        return NULL;

    if (key < root->data)
        root->left = deleteNode(root->left, key);
    else if (key > root->data)
        root->right = deleteNode(root->right, key);
    else {
        if (root->left == NULL) {
            struct Node* temp = root->right;
            free(root);
            return temp;
        }
        else if (root->right == NULL) {
            struct Node* temp = root->left;
            free(root);
            return temp;
        }

        struct Node* temp = findMin(root->right);
        root->data = temp->data;
        root->right = deleteNode(root->right, temp->data);
    }

    return root;
}

void inorder(struct Node* root) {
    if (root != NULL) {
        inorder(root->left);
        printf("%d ", root->data);
        inorder(root->right);
    }
}

int main() {
    struct Node* root = NULL;
    int arr[] = {50, 30, 70, 20, 40, 60, 80};
    int key;

    for (int i = 0; i < 7; i++)
        root = insert(root, arr[i]);

    printf("Original BST: ");
    inorder(root);

    printf("\nEnter value to delete: ");
    scanf("%d", &key);

    root = deleteNode(root, key);

    printf("Updated BST: ");
    inorder(root);

    return 0;
}

Sample Output

Original BST: 20 30 40 50 60 70 80
Enter value to delete: 50
Updated BST: 20 30 40 60 70 80

Concept learned: Node deletion, dynamic memory management, inorder successor and handling different BST deletion cases.

Exercise 6: Count Total Nodes, Leaf Nodes and Internal Nodes

Problem: Construct a BST using the elements 45, 25, 65, 15, 35, 55, 75 and 85. Write a C program to count the total number of nodes, leaf nodes and internal nodes.

Step-by-Step Solution

  1. Construct the BST using recursive insertion.
  2. For total nodes, count the current node plus the nodes in both subtrees.
  3. A leaf node is a node whose left and right pointers are both NULL.
  4. An internal node is a non-leaf node with at least one child.
  5. Use separate recursive functions to calculate each count.

C Program

#include <stdio.h>
#include <stdlib.h>

struct Node {
    int data;
    struct Node *left, *right;
};

struct Node* insert(struct Node* root, int value) {
    if (root == NULL) {
        struct Node* temp = malloc(sizeof(struct Node));
        temp->data = value;
        temp->left = temp->right = NULL;
        return temp;
    }

    if (value < root->data)
        root->left = insert(root->left, value);
    else if (value > root->data)
        root->right = insert(root->right, value);

    return root;
}

int countNodes(struct Node* root) {
    if (root == NULL)
        return 0;
    return 1 + countNodes(root->left) + countNodes(root->right);
}

int countLeaves(struct Node* root) {
    if (root == NULL)
        return 0;

    if (root->left == NULL && root->right == NULL)
        return 1;

    return countLeaves(root->left) + countLeaves(root->right);
}

int countInternal(struct Node* root) {
    if (root == NULL || (root->left == NULL && root->right == NULL))
        return 0;

    return 1 + countInternal(root->left) + countInternal(root->right);
}

int main() {
    struct Node* root = NULL;
    int arr[] = {45, 25, 65, 15, 35, 55, 75, 85};

    for (int i = 0; i < 8; i++)
        root = insert(root, arr[i]);

    printf("Total Nodes: %d\n", countNodes(root));
    printf("Leaf Nodes: %d\n", countLeaves(root));
    printf("Internal Nodes: %d\n", countInternal(root));

    return 0;
}

Expected Output

Total Nodes: 8
Leaf Nodes: 4
Internal Nodes: 4

Concept learned: Recursive counting, identifying leaf nodes and understanding the structure of a binary tree.

Important Binary Search Tree Practice Challenges

After completing the solved exercises, attempt these additional challenges without looking at the solutions. These questions will help strengthen your understanding of BST operations.

  1. Write a C program to calculate the height of a Binary Search Tree.
  2. Write a program to find the second-largest element in a BST.
  3. Write a program to count the number of nodes having exactly one child.
  4. Write a program to print all elements of a BST that are greater than a number entered by the user.
  5. Write a menu-driven BST program that allows insertion, searching, deletion and traversal operations.

Time Complexity of Binary Search Tree Operations

OperationAverage CaseWorst Case
InsertionO(log n)O(n)
SearchingO(log n)O(n)
DeletionO(log n)O(n)
Inorder TraversalO(n)O(n)
Finding MinimumO(log n)O(n)

Note: The average-case complexity assumes a reasonably balanced tree. An unbalanced BST can behave like a linked list, resulting in O(n) search, insertion and deletion operations.

Frequently Asked Questions About Binary Search Tree Using C

Find answers to common questions about implementing and understanding Binary Search Trees in C programming.

Frequently Asked Questions

⚡ Live Output