Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

#include <stdio.

h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

#define MAX_EXPR_SIZE 100

// Structure for a node of the expression tree


struct TreeNode {
char data;
struct TreeNode *left;
struct TreeNode *right;
};

// Function to create a new node


struct TreeNode *createNode(char data) {
struct TreeNode *newNode = (struct TreeNode *)malloc(sizeof(struct TreeNode));
if (newNode == NULL) {
fprintf(stderr, "Memory allocation failed\n");
exit(EXIT_FAILURE);
}
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}

// Function to check if a character is an operator


int isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/');
}

// Function to build expression tree from postfix expression


struct TreeNode *buildExpressionTree(char postfix[]) {
struct TreeNode *stack[MAX_EXPR_SIZE]; // Assuming the expression won't exceed
100 characters
int top = -1;
for (int i = 0; postfix[i] != '\0'; i++) {
if (isalnum(postfix[i])) {
stack[++top] = createNode(postfix[i]);
} else if (isOperator(postfix[i])) {
struct TreeNode *operatorNode = createNode(postfix[i]);
operatorNode->right = stack[top--];
operatorNode->left = stack[top--];
stack[++top] = operatorNode;
}
}
return stack[top];
}

// Helper function to check if brackets are required


int needBrackets(char c) {
return (c == '+' || c == '-') ? 1 : 0;
}

// Function to print infix form of expression tree


void printInfix(struct TreeNode *root) {
if (root != NULL) {
if (root->left != NULL && needBrackets(root->data)) {
printf("(");
printInfix(root->left);
printf(")");
} else {
printInfix(root->left);
}
printf("%c", root->data);
if (root->right != NULL && needBrackets(root->data)) {
printf("(");
printInfix(root->right);
printf(")");
} else {
printInfix(root->right);
}
}
}

int main() {
char postfix[MAX_EXPR_SIZE];
printf("Enter postfix expression: ");
scanf("%s", postfix);

struct TreeNode *root = buildExpressionTree(postfix);

printf("Infix form of expression: ");


printInfix(root);
printf("\n");

return 0;
}

You might also like