Implementation of Binary Tree
Implementation of Binary Tree Menu Driven Program.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *left, *right;
}node;
node *create();
void inorder(node *t);
void preorder(node *t);
void postorder(node *t);
node *create()
{
node *p;
int x;
printf("\n Enter the data (-1 for null node)");
scanf("%d",&x);
if(x==-1)
return NULL;
p=(node *) malloc(sizeof(node));
p->data=x;
printf("\n Enter the left Child of %d", x);
p->left=create();
printf("\n Enter the right Child of %d", x);
p->right=create();
return p;
}
void main()
{
node *root=NULL, *p;
int op;
int x;
clrscr();
do
{
flushall();
printf("\n\n1) Create");
printf("\n2) Preorder \n 3) Inorder \n4)
Postorder\n 5) Quit\t");
scanf("%d", &op);
switch(op)
{
case 1: root=create();
printf("\n Inorder Traversal
on the tree\n");
inorder(root);
break;
case 2:
preorder(root);
break;
case 3:
inorder(root);
break;
case 4:
postorder(root);
break;
}
}while(o!=5);
}
void inorder(node *t)
{
if(t!=NULL)
{
inorder(t->left);
printf("%d\t", t->data);
inorder(t->right);
}
}
void preorder(node *t)
{
if(t!=NULL)
{
printf("%d\t", t->data);
preorder(t->left);
preorder(t->right);
}
}
void postorder(node *t)
{
if(t!=NULL)
{
postorder(t->left);
postorder(t->right);
printf("%d\t", t->data);
}
}
Output
Comments
Post a Comment