Pre Order, Post order, In order Implement Binary Tree using linked list

How to write a C Program to implement Binary Tree using linked list. Display the three.. Search and item from the tree with proper message and traverse the tree in Pre Order, Post order and In order in C Programming Language ?


Solution:



/*
Write a program to implement Binary Tree using linked list. Display the three.. Search and item from
the tree with proper message and traverse the tree in
i) Pre Order
ii)Post order
iii) In order
*/

#include< stdio.h>
#include< conio.h>
#include< alloc.h>
struct bstree
{
int data;
struct bstree *lchild,*rchild;
};/*End of struct bstree*/
typedef struct bstree BST;
BST *root=NULL;
BST *create(BST *,int);
void inorder(BST *);
void preorder(BST *);
void postorder(BST *);
void search(BST *,int);
void main()
{
int ch;
int ele;
while(1)
{
clrscr();
printf("\nPress 1 For Insertion.");
printf("\nPress 2 For Inorder Traversal.");
printf("\nPress 3 For Preorder Traversal.");
printf("\nPress 4 For Postorder Traversal.");
printf("\nPress 5 For Search Item.");
printf("\nPress 6 For Exit.");
printf("\nEnter Your Choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\nEnter Element: ");
scanf("%d",&ele);
root=create(root,ele);
getch();
break;
case 2:
inorder(root);
getch();
break;
case 3:
preorder(root);
getch();
break;
case 4:
postorder(root);
getch();
break;
case 5:
printf("\nEnter Element To Be Searched: ");
scanf("%d",&ele);
search(root,ele);
getch();
break;
case 6:
exit(0);
break;
default:
printf("\nInvalid Choice... Try Again..");
getch();
}/*End of switch(ch)*/
}/*End of while(1)*/
}/*End of void main()*/
BST *create(BST *node,int x)
{
if(node==NULL)
{
node=(BST *)malloc(sizeof(BST));
node->lchild=NULL;
node->rchild=NULL;
node->data=x;
}/*End of if(node==NULL)*/
else if(xdata)
node->lchild=create(node->lchild,x);
else if(x>=node->data)
node->rchild=create(node->rchild,x);
return node;
}/*End of BST *create(BST *,int)*/
void inorder(BST *node)
{
if(node!=NULL)
{
inorder(node->lchild);
printf("%d ",node->data);
inorder(node->rchild);
}/*End of if(node!=NULL)*/
}/*End of void inorder(BST *)*/
void preorder(BST *node)
{
if(node!=NULL)
{
printf("%d ",node->data);
preorder(node->lchild);
preorder(node->rchild);
}/*End of if(node!=NULL)*/
}/*End of void preorder(BST *node)*/
void postorder(BST *node)
{
if(node!=NULL)
{
postorder(node->lchild);
postorder(node->rchild);
printf("%d ",node->data);
}/*End of if(node!=NULL)*/
}/*End of void postorder(BST *node)*/
void search(BST *node,int num)
{
if(node==NULL)
printf("\nThe Number Is Not Present.");
else if(node->data==num)
printf("\nElement Found.");
else if(node->data>num)
search(node->lchild,num);
else
search(node->rchild,num);
}/*End of void search(BST *node,int num)*/


Learn More :