EXP No.
: 06
Kunal Shantaram Bhoi (2022600007)
CSE (AIML) Batch : A
--------------------------------------------------------------------------------
Problem Statement :
Create an expression tree from given preorder expression traversal and perform evaluation.
Program :
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
struct TreeNode {
char data;
struct TreeNode* left;
struct TreeNode* right;
};
struct StackNode {
struct TreeNode* treeNode;
struct StackNode* next;
};
struct TreeNode* createNode(char data) {
struct TreeNode* newNode = (struct TreeNode*)malloc(sizeof(struct TreeNode));
if (newNode == NULL) {
printf("Memory allocation error\n");
exit(EXIT_FAILURE);
}
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
struct StackNode* createStackNode(struct TreeNode* treeNode) {
struct StackNode* newNode = (struct StackNode*)malloc(sizeof(struct StackNode));
if (newNode == NULL) {
printf("Memory allocation error\n");
exit(EXIT_FAILURE);
}
newNode->treeNode = treeNode;
newNode->next = NULL;
return newNode;
}
void push(struct StackNode** top, struct TreeNode* treeNode) {
struct StackNode* newNode = createStackNode(treeNode);
newNode->next = *top;
*top = newNode;
}
struct TreeNode* pop(struct StackNode** top) {
if (*top == NULL) {
printf("Stack underflow\n");
exit(EXIT_FAILURE);
}
struct TreeNode* treeNode = (*top)->treeNode;
struct StackNode* temp = *top;
*top = (*top)->next;
free(temp);
return treeNode;
}
int isOperator(char ch) {
return (ch == '+' || ch == '-' || ch == '*' || ch == '/');
}
struct TreeNode* buildExpressionTree(char postfix[]) {
struct StackNode* stack = NULL;
for (int i = 0; postfix[i] != '\0'; ++i) {
struct TreeNode* newNode = createNode(postfix[i]);
if (isalnum(postfix[i])) {
push(&stack, newNode);
} else if (isOperator(postfix[i])) {
newNode->right = pop(&stack);
newNode->left = pop(&stack);
push(&stack, newNode);
}
}
return pop(&stack);
}
void printPostorder(struct TreeNode* node) {
if (node == NULL) {
return;
}
printPostorder(node->left);
printPostorder(node->right);
printf("%c ", node->data);
}
int evaluateExpressionTree(struct TreeNode* root) {
if (root == NULL) {
return 0;
}
if (!isOperator(root->data)) {
return root->data - '0';
}
int leftValue = evaluateExpressionTree(root->left);
int rightValue = evaluateExpressionTree(root->right);
switch (root->data) {
case '+':
return leftValue + rightValue;
case '-':
return leftValue - rightValue;
case '*':
return leftValue * rightValue;
case '/':
return leftValue / rightValue;
default:
return 0;
}
}
int main() {
char postfixExpression[50];
printf("Enter postfix expression: ");
scanf("%s", postfixExpression);
struct TreeNode* root = buildExpressionTree(postfixExpression);
printf("Postorder traversal of the expression tree: ");
printPostorder(root);
printf("\n");
int result = evaluateExpressionTree(root);
printf("Result of the expression: %d\n", result);
return 0;
}
Output :