Write a program to create an expression tree for a given PREFIX expression and traverse the tree to check the correctness of the prefix expression.
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
char dt;
struct node *lt, *rt;
} node;
char* addition(node** x, char* ch)
{
if (*ch == '\0')
return '\0';
while (1) {
char* y = "null";
if (*x == NULL) {
node* n = (node*)malloc(sizeof(node));
n->dt = *ch;
n->lt = NULL;
n->rt = NULL;
*x = n;
}
else {
if (*ch >= 'a' && *ch <= 'z') {
return ch;
}
y = addition(&(*x)->lt, ch + 1);
y = addition(&(*x)->rt, y + 1);
return y;
}
}
}
void infixExpression(node* x)
{
if (x == NULL) {
return;
}
else {
infixExpression(x->lt);
printf("%c ", x->dt);
infixExpression(x->rt);
}
}
void postfixExpression(node* x)
{
if (x == NULL) {
return;
}
else {
postfixExpression(x->lt);
postfixExpression(x->rt);
printf("%c ", x->dt);
}
}
int main()
{
node* x = NULL;
char ch[] = "*+xy-wz";
addition(&x, ch);
printf("Infix expression:\n ");
infixExpression(x);
printf("\n");
printf("Postfix expression:\n ");
postfixExpression(x);
return 0;
}
Comments
Leave a comment