C Program: Dynamic BST — Insert & Search
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program to Dynamically Allocate Memory for a Binary Search Tree and Implement Insert and Search

📑 On this page:
  • Purpose & Objective
  • What is a Binary Search Tree?
  • Real-Life Applications
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How to model a BST node with struct Node (data, left, right)
  • How to allocate nodes with malloc() and check for NULL
  • How to insert recursively following the BST property
  • How to search recursively and return the found node
  • How to traverse the tree in inorder, preorder, and postorder
  • How to free the entire tree recursively without leaks

Purpose & Objective

We will cover each concept step by step to develop a C program that allocates memory dynamically for a Binary Search Tree (BST) and implements functions to add and search for elements.

This program demonstrates the basic operations of a BST using Dynamic Memory Allocation (DMA) in C — explaining the purpose, real-life applications, and giving detailed output with code explanation.

Purpose: To implement a BST using dynamic memory allocation, building a solid understanding of binary trees — and specifically BSTs — which are essential for efficient search, insertion, and deletion operations.

💡 Quick Definition: A Binary Search Tree is a binary tree where every node's value is greater than all values in its left subtree and less than all values in its right subtree. This property makes search, insert, and delete operations O(h) — where h is the tree height — typically O(log n) for balanced trees.

C program to dynamically allocate memory for a Binary Search Tree, insert and search for elements

What is a Binary Search Tree?

Every node in a BST has at most two children. The ordering rule lets us skip entire subtrees during search — that's what makes BSTs fast.

Operation Rule Complexity
insert(x)Compare x with node; go left if smaller, right if largerO(h)
search(x)Same traversal as insert — stop when found or when reaching NULLO(h)
Inorder traversalLeft → Root → Right — produces sorted orderO(n)
PreorderRoot → Left → RightO(n)
PostorderLeft → Right → RootO(n)

Real-Life Applications

Binary Search Trees are used in a variety of real-life applications:

Database Indexing

Using a binary tree eliminates the need to sort the master list before searching. When you have a sorted list, you can effectively use binary search to search through the list. Database indexes are data structures of indexed data — binary search calculates the next midpoint at each step.

File Systems

File systems use BSTs to maintain directory structures for quick lookup of files and directories. For example, the Windows NTFS file system uses BSTs to store the Master File Table (MFT), which contains information about all files on the drive.

Computer Networks

Binary search trees can be used in computer networks to store routing tables.

Spell Checkers

A binary tree must be built before spell checking. Each node holds a letter — starting with each letter as root. The left and right children hold further letters, forming potentially valid words. Dictionary applications use BSTs to efficiently store and search words.

Complete C Program

Program: Dynamically allocate a BST and implement insert, search, and traversal

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

/* Structure for a BST node */
struct Node {
    int data;
    struct Node *left;
    struct Node *right;
};

/* Function to create a new BST node */
struct Node *createNode(int data) {
    struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
    if (newNode == NULL) {
        printf("Memory allocation failed.\n");
        exit(1);
    }
    newNode->data = data;
    newNode->left = NULL;
    newNode->right = NULL;
    return newNode;
}

/* Function to insert a node into the BST */
struct Node *insert(struct Node *root, int data) {
    if (root == NULL) {
        return createNode(data);
    }
    if (data < root->data) {
        root->left = insert(root->left, data);
    } else if (data > root->data) {
        root->right = insert(root->right, data);
    }
    return root;
}

/* Function to search for a node in the BST */
struct Node *search(struct Node *root, int key) {
    if (root == NULL || root->data == key) {
        return root;
    }
    if (key < root->data) {
        return search(root->left, key);
    }
    return search(root->right, key);
}

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

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

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

/* Function to free all nodes of the BST */
void freeBST(struct Node *root) {
    if (root != NULL) {
        freeBST(root->left);
        freeBST(root->right);
        free(root);
    }
}

/* Main function to demonstrate BST operations */
int main() {
    struct Node *root = NULL;
    struct Node *result;
    int choice, data, key;

    printf("Binary Search Tree Operations\n");
    while (1) {
        printf("\n1. Insert\n");
        printf("2. Search\n");
        printf("3. Display Inorder\n");
        printf("4. Display Preorder\n");
        printf("5. Display Postorder\n");
        printf("6. Exit\n");
        printf("Enter your choice: ");
        scanf("%d", &choice);

        switch (choice) {
            case 1:
                printf("Enter data to insert: ");
                scanf("%d", &data);
                root = insert(root, data);
                printf("%d inserted into the tree.\n", data);
                break;
            case 2:
                printf("Enter data to search: ");
                scanf("%d", &key);
                result = search(root, key);
                if (result != NULL) {
                    printf("%d found in the tree.\n", key);
                } else {
                    printf("%d not found in the tree.\n", key);
                }
                break;
            case 3:
                printf("Inorder traversal: ");
                inorder(root);
                printf("\n");
                break;
            case 4:
                printf("Preorder traversal: ");
                preorder(root);
                printf("\n");
                break;
            case 5:
                printf("Postorder traversal: ");
                postorder(root);
                printf("\n");
                break;
            case 6:
                printf("Exiting program.\n");
                freeBST(root);
                exit(0);
            default:
                printf("Invalid choice. Please try again.\n");
        }
    }

    return 0;
}
                                    

Program Output

Binary Search Tree Operations

1. Insert
2. Search
3. Display Inorder
4. Display Preorder
5. Display Postorder
6. Exit
Enter your choice: 1
Enter data to insert: 10
10 inserted into the tree.

1. Insert
2. Search
3. Display Inorder
4. Display Preorder
5. Display Postorder
6. Exit
Enter your choice: 1
Enter data to insert: 5
5 inserted into the tree.

1. Insert
2. Search
3. Display Inorder
4. Display Preorder
5. Display Postorder
6. Exit
Enter your choice: 1
Enter data to insert: 20
20 inserted into the tree.

1. Insert
2. Search
3. Display Inorder
4. Display Preorder
5. Display Postorder
6. Exit
Enter your choice: 2
Enter data to search: 5
5 found in the tree.

1. Insert
2. Search
3. Display Inorder
4. Display Preorder
5. Display Postorder
6. Exit
Enter your choice: 2
Enter data to search: 15
15 not found in the tree.

1. Insert
2. Search
3. Display Inorder
4. Display Preorder
5. Display Postorder
6. Exit
Enter your choice: 3
Inorder traversal: 5 10 20

1. Insert
2. Search
3. Display Inorder
4. Display Preorder
5. Display Postorder
6. Exit
Enter your choice: 4
Preorder traversal: 10 5 20

1. Insert
2. Search
3. Display Inorder
4. Display Preorder
5. Display Postorder
6. Exit
Enter your choice: 5
Postorder traversal: 5 20 10

1. Insert
2. Search
3. Display Inorder
4. Display Preorder
5. Display Postorder
6. Exit
Enter your choice: 6
Exiting program.
                                

Step-by-Step Explanation

This program shows how various operations are performed on a Binary Search Tree. It includes functions to insert, search, and traverse nodes in three orders — inorder, preorder, and postorder. Here's a walkthrough of the run.

1. Initialization and main menu:

struct Node *root = NULL;
                                

On startup, the tree is empty (root = NULL). The user is then shown the operations menu:

Binary Search Tree Operations
1. Insert
2. Search
3. Display Inorder
4. Display Preorder
5. Display Postorder
6. Exit
Enter your choice:
                                

2. Insert Operation:

Enter data to insert: 10
10 inserted into the tree.
                                

createNode allocates a new node with malloc, sets left and right to NULL, and returns it. Then insert navigates to the correct position — comparing the new value with each node's data and recursing left or right — until it finds an empty spot.

3. Search Operation:

Enter data to search: 5
5 found in the tree.
                                

search starts at the root and follows the same comparison logic — go left if the key is smaller, right if larger. It stops either when it finds a matching node or hits NULL.

4. Inorder Traversal:

Inorder traversal: 5 10 20
                                

Inorder visits left subtree → root → right subtree. For a BST, this produces the values in ascending sorted order. That's the signature property of a valid BST.

5. Preorder Traversal:

Preorder traversal: 10 5 20
                                

Preorder visits root first, then left, then right. Useful for serializing the tree or copying it — the root comes first, so reconstructing the tree later is straightforward.

6. Postorder Traversal:

Postorder traversal: 5 20 10
                                

Postorder visits left → right → root. It's the natural order for freeing a tree — you free children before the parent, which is exactly how freeBST works.

🎯 Key Takeaway: The three traversals are the three natural orders in which you might visit every node of the tree. Inorder sorts. Preorder copies. Postorder frees. Every tree algorithm is built from one of these three patterns.

Frequently Asked Questions

1. What happens if I insert duplicate values?

In this version, duplicates are silently ignored (the else if (data > root->data) branch skips them). If you want to keep duplicates, add a counter to each node or route equal values to the right subtree.

2. Why does search use recursion?

Because the tree is recursively defined — left subtree is a tree, right subtree is a tree. The recursive search mirrors the structure. An iterative version is easy too and avoids stack depth on deep trees.

3. What's the worst-case time complexity?

O(n) — when the tree degenerates into a linked list (e.g., inserting sorted values 1, 2, 3, 4, ...). Self-balancing trees like AVL or Red-Black fix this by guaranteeing O(log n).

4. Why is freeBST post-order?

Because you must free the children before freeing their parent — otherwise you'd try to access root->left and root->right after they were already freed. Post-order guarantees children are gone before the parent is released.

💡 Tip: Compile with gcc -fsanitize=address -g to catch use-after-free and leaks instantly — especially important with recursive frees.

📖 Related Tutorials

  • malloc in C
  • free in C
  • 4. Dynamic Linked List and Reverse
  • 5. Dynamic Stack — Push and Pop
  • 7. Dynamic Queue — Enqueue and Dequeue
  • All DMA Assignments

Previous Topic: -->> 5. Dynamic Stack & Push/Pop   ||   Next topic: -->> 7. Dynamic Queue & Enqueue/Dequeue


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.