Here we are going to write a program to create a BST (binary search tree) in c using recursive way. We will build tree by taking data from the user using build tree function and will print the tree using any of the traversals here we will use in-order traversal.
Basic Property of BST is: In a BST, for each node, all the elements in left subtree is less than the root node and all the elements in right subtree is greater than the root node.
Example -We will build this binary search tree -
5
/ \
4 6
/ \
2 7
/ \
1 3
As we are going to print the binary search tree using in order traversal so Output will be like this -
1 2 3 4 5 6 7
Program to create a BST (Binary Search Tree) in C
#include <stdio.h>
#include <malloc.h>
struct node{
int data;
struct node* left;
struct node* right;
};
struct node* create(struct node* root,int d){
struct node* n=(struct node*)malloc(sizeof(struct node));
n->data=d;
n->left=NULL;
n->right=NULL;
if(root==NULL){
root=n;
return root;
}
if(d <= (root)->data){
root->left=create(root->left,d);
}
else{
root->right=create(root->right,d);
}
return root;
}
void inorder(struct node* root){
if(root!=NULL){
inorder(root->left);
printf("%d ",root->data);
inorder(root->right);
}
}
void preorder(struct node* root){
if(root!=NULL){
printf("%d ",root->data);
preorder(root->left);
preorder(root->right);
}
}
int main(){
struct node* root=NULL;
root=create(root,5);
create(root,4);
create(root,2);
create(root,6);
create(root,7);
create(root,1);
create(root,3);
inorder(root);
preorder(root);
return 0;
}
Output
1 2 3 4 5 6 7
Post a Comment
If you have any doubts, please let me know