/* FORMING A TREE USING PREFIX EXPRESSION AND THEN PREFORM
ALL THE TRAVERSALS(RECURSIVE) */
#include<stdio.h>
#include<ctype.h>
struct tree
{
char data;
struct tree *left,*right;
};
typedef struct tree btree;
char prefix[20];
btree *stack[20];
int top;
main()
{
btree *create(void);
void inorder(btree *temp);
void preorder(btree *temp);
void postorder(btree *temp);
void push(btree *temp);
btree *pop(void);
btree *root;
clrscr();
printf("PLEASE ENTER THE PREFIX EXPRESSION:");
gets(prefix);
root=create();
printf("\nTHE INORDER TRAVERSAL IS:");
inorder(root);
printf("\nTHE PREORDER TRAVERSAL IS:");
preorder(root);
printf("\nTHE POSTORDER TRAVERSAL IS:");
postorder(root);
getch();
}
btree *create(void)
{
btree *head,*temp,*temp1;
int i=0,n;
top=-1;
head=(btree*)malloc(sizeof(btree));
temp=head;
temp->data=prefix[i];
i++;
temp->right=temp->left=NULL;
push(temp);
n=strlen(prefix);
while(top!=-1)
{
while(!isalnum(prefix[i]))
{
temp=pop();
temp1=(btree*)malloc(sizeof(btree));
temp1->right=temp1->left=NULL;
temp->left=temp1;
temp1->data=prefix[i];
i++;
push(temp);
push(temp1);
}
temp1=(btree*)malloc(sizeof(btree));
temp=pop();
temp->left=temp1;
temp1->data=prefix[i];
temp1->left=temp1->right=NULL;
push(temp);
do {
temp=pop();
i++;
temp1=(btree*)malloc(sizeof(btree));
temp->right=temp1;
temp1->data=prefix[i];
temp1->right=temp1->left=NULL;
if(!isalpha(prefix[i]))
{i++;
push(temp1);
break;}
}while(top!=-1);
}
return(head);
}
void push(btree *temp)
{
top++;
stack[top]=temp;
return;
}
btree *pop(void)
{
return(stack[top--]);
}
void inorder(btree *temp)
{
if(temp)
{
inorder(temp->left);
putch(temp->data);
inorder(temp->right);
}
return;
}
void preorder(btree *temp)
{
if(temp)
{
putch(temp->data);
preorder(temp->left);
preorder(temp->right);
}
return;
}
void postorder(btree *temp)
{
if(temp)
{
postorder(temp->left);
postorder(temp->right);
putch(temp->data);
}
return;
}
No comments:
Post a Comment