Program for Binary Search Tree in C

Here you will get the program for twofold search tree in C.

A Binary Search Tree (BST) is a parallel tree in which every one of the components put away in the left subtree of hub x is less then x and all components put away in the privilege subtree of hub x are more noteworthy then x.

Beneath I have shared a C program for paired hunt tree addition. Subsequent to embeddings every one of the hubs I am showing the hubs by preorder traversal (root, left kid, right youngster).

Program for Binary Search Tree in C

#include<stdio.h>
#include<stdlib.h>
 
typedef struct BST
{
	int data;
	struct BST *left;
	struct BST *right;
}node;
 
node *create();
void insert(node *,node *);
void preorder(node *);
 
int main()
{
	char ch;
	node *root=NULL,*temp;
	
	do
	{
		temp=create();
		if(root==NULL)
			root=temp;
		else	
			insert(root,temp);
			
		printf("nDo you want to enter more(y/n)?");
		getchar();
		scanf("%c",&ch);
	}while(ch=='y'|ch=='Y');
	
	printf("nPreorder Traversal: ");
	preorder(root);
	return 0;
}
 
node *create()
{
	node *temp;
	printf("nEnter data:");
	temp=(node*)malloc(sizeof(node));
	scanf("%d",&temp->data);
	temp->left=temp->right=NULL;
	return temp;
}
 
void insert(node *root,node *temp)
{
	if(temp->data<root->data)
	{
		if(root->left!=NULL)
			insert(root->left,temp);
		else
			root->left=temp;
	}
	
	if(temp->data>root->data)
	{
		if(root->right!=NULL)
			insert(root->right,temp);
		else
			root->right=temp;
	}
}
 
void preorder(node *root)
{
	if(root!=NULL)
	{
		printf("%d ",root->data);
		preorder(root->left);
		preorder(root->right);
	}
}

Output

Remark beneath in the event that you are confronting any issue in this program for parallel hunt tree in C.

Leave a Comment

error: Alert: Content is protected!!