A binary search tree in C is a special type of binary tree where each node follows a specific order: left child < parent < right child. This structure is useful for efficient searching, insertion, and deletion operations.
In this article, we will write a C program that creates a binary search tree (BST) by inserting elements provided by the user and then displaying the BST using in-order traversal.
This guide is perfect for students learning data structures and C programming.
What is a Binary Search Tree?
A binary search tree (BST) is a data structure in which:
- Each node has at most two children.
- Left child contains values less than the node.
- Right child contains values greater than the node.
C Program: Binary Search Tree in C
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* left;
struct Node* right;
};
struct Node* createNode(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
struct Node* insert(struct Node* root, int value) {
if (root == NULL) {
return createNode(value);
}
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 values[] = {50, 30, 70, 20, 40, 60, 80};
int n = sizeof(values)/sizeof(values[0]);
for (int i = 0; i < n; i++) {
root = insert(root, values[i]);
}
printf("In-order traversal of Binary Search Tree:\n");
inOrder(root);
return 0;
}
Explanation of the Program
- createNode(): Allocates memory and initializes a new node.
- insert(): Recursively inserts a value into the correct location in the BST.
- inOrder(): Performs in-order traversal (Left → Root → Right) to display sorted tree elements.
This binary search tree in C is built using recursion and dynamic memory allocation.
Applications of Binary Search Tree in C
- Fast searching and retrieval of data
- Implementation of associative arrays
- Used in databases and file systems