The binary search tree program in c is a simple program to implement a binary search tree.

Binary search tree definition
Binary search tree (BST) is a binary tree in which each node has a value greater than every node of left subtree and less than every node of the right subtree.

Binary search tree insertion in c

  1. Compare data with data of the root node.
  2. If data < data of node then compare with data of left child node and insert it to the proper place.
  3. if data > data of node then compare with data of the right child node and insert it to the proper place.

Binary search tree deletion

In deletion, if the deleting node is leaf node then simply delete node.
If the node which is deleting has some child then after deleting the node adjust its child according to the Binary search tree properly.

Binary Search Tree Traversal

  1. Preorder traversal
  2. Inorder traversal
  3. Postorder traversal

Algorithm for Binary search tree

  1. Create s structure with left-right and data
  2. Write a function to create node dynamically
  3. Declare function to insert a node.
  4. Write a function to traverse the tree(inorder)
  5. Write the main function
  6. Create some nodes.
  7. Traverse the tree

Binary search tree program in c

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

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

struct node* createNode(value){
struct node* newNode = malloc(sizeof(struct node));
newNode->data = value;
newNode->left = NULL;
newNode->right = NULL;

return newNode;
}


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;
}

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


int main(){
struct node *root = NULL;
root = insert(root, 8);
insert(root, 3);
insert(root, 1);
insert(root, 6);
insert(root, 7);
insert(root, 10);
insert(root, 14);
insert(root, 4);
printf("Binary search tree\n");
inorder(root);
}

Output:

Binary search tree program in c

Write A Comment