Answer to Question #268583 in C for gikovi

Question #268583

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.


1
Expert's answer
2021-11-19T17:14:17-0500
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS