C Program Implement Binary Search Tree And Its Traversals

How to write a c program binary tree and its traversals in C Programming Language ?



https://en.wikipedia.org/wiki/Tree_traversal

Solution:
/* Binary tree and its traversals */

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

struct btree* create(struct btree*, int);
void inorder(struct btree*);
void preorder(struct btree*);
void postorder(struct btree*);
void levelorder(struct btree*);

int l=0,r=0,i;

struct btree
{
int data;
struct btree *lptr, *rptr;
};

int main()
{

struct btree *root;
root=NULL;


int value,b,n;

do
{
printf("\nCase options\n1->Enter elements into btree\n2->Inorder print\n3->Preorder print\n4->Postorder print\n5->Levelorder print\n0->Exit\n");
scanf("%d",&b);

switch(b)
{
case 1: printf("\nHow many elements u want to enter the elements in the btree\n");
scanf("%d",&n);

for(i=0;i<n;i++)
{
printf("\nEnter the value into the btree\n");
scanf("%d",&value);
root = create(root,value);
}
printf("No. of nodes:\nTo left: %d\nTo Right: %d\nIn Totality: %d\n",l,r, (l+r+1) );
break;

case 2: printf("\n Inorder print\n");
inorder(root);
break;

case 3: printf("\n Pre order print\n");
preorder(root);
break;

case 4: printf("\n Post order print\n");
postorder(root);
break;

case 5: printf("\n Level order print\n");
levelorder(root);
break;

case 0: break;
}
if( b==0)
exit (0);
}
while(b!=0);
}


struct btree* create(struct btree *root, int value)
{
struct btree *temp,*temp1;
struct btree *nn;
if(root == NULL)
{
printf("\nThe newnode is the root node\n");
nn = (struct btree*)malloc(sizeof(struct btree));

nn->data = value;
nn->lptr = NULL;
nn->rptr = NULL;
root=nn;
}

else if (root != NULL)
{
temp = root;

while (temp != NULL)
{
temp1=temp;

if(temp->data >= value)
{
if (temp->data != value)
temp= temp->lptr;
else
{
printf("\nRe-enter a unique value\n");
i--;
break;
}
}

else if(temp->data <= value)
{
if(temp->data != value)
temp= temp->rptr;

else
{
printf("\nRe-enter a unique value\n");
i--;
break;
}
}
}


if(temp1->data >value)
{
temp1->lptr= (struct btree*)malloc (sizeof(struct btree*));
l++;
temp1=temp1->lptr;
temp1->data=value;
temp1->lptr=temp1->rptr=NULL;
}
if(temp1->data <value)
{
temp1->rptr= (struct btree*)malloc (sizeof(struct btree*));
r++;
temp1=temp1->rptr;
temp1->data=value;
temp1->lptr=temp1->rptr=NULL;

}
}

return root;

}


void inorder (struct btree* root)
{
if( root !=NULL)
{
inorder(root->lptr);
printf("%d\n", root->data);
inorder(root->rptr);
}
}

void preorder (struct btree* root)
{
if( root !=NULL)
{
printf("%d\n", root->data);
preorder(root->lptr);
preorder(root->rptr);
}
}

void postorder (struct btree* root)
{
if( root !=NULL)
{
postorder(root->lptr);
postorder(root->rptr);
printf("%d\n", root->data);
}
}

void levelorder (struct btree* root)
{
static struct btree *t1, *t2;
t1=root;

printf("%d\n", root->data);

levelorder(t1->lptr);
printf("%d\n", t1->data);

t2=root;

levelorder(t2->rptr);
printf("%d\n", t2->data);
}


Learn More :