编写程序,实现以下功能: 1、对于给定的中缀表达式,创建与其对应的表达式树(二叉树),用二叉链表存储; 2、利用表达式树进行表达式求值。
时间: 2024-02-25 15:56:32 浏览: 139
好的,我可以给你提供一个C语言的实现,实现中缀表达式转换为表达式树并求值的功能。代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
typedef struct TreeNode {
char data;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
typedef struct Stack {
int top;
int size;
TreeNode **data;
} Stack;
Stack *createStack(int size) {
Stack *S = (Stack *)malloc(sizeof(Stack));
S->size = size;
S->top = -1;
S->data = (TreeNode **)malloc(sizeof(TreeNode *) * size);
return S;
}
void push(Stack *S, TreeNode *x) {
if (S->top == S->size - 1) {
printf("Stack overflow\n");
return;
}
S->data[++S->top] = x;
}
TreeNode *pop(Stack *S) {
if (S->top == -1) {
printf("Stack underflow\n");
return NULL;
}
return S->data[S->top--];
}
TreeNode *createNode(char data) {
TreeNode *newNode = (TreeNode *)malloc(sizeof(TreeNode));
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
int isOperator(char data) {
if (data == '+' || data == '-' || data == '*' || data == '/')
return 1;
return 0;
}
TreeNode *buildExpressionTree(char *expression) {
Stack *S = createStack(strlen(expression));
TreeNode *root = NULL;
for (int i = 0; expression[i]; i++) {
if (expression[i] == '(') {
push(S, createNode(expression[i]));
} else if (isdigit(expression[i])) {
TreeNode *node = createNode(expression[i]);
push(S, node);
} else if (isOperator(expression[i])) {
TreeNode *node = createNode(expression[i]);
node->right = pop(S);
node->left = pop(S);
push(S, node);
} else if (expression[i] == ')') {
pop(S);
}
}
if (!isEmpty(S)) {
root = pop(S);
}
free(S->data);
free(S);
return root;
}
int evaluateExpressionTree(TreeNode *root) {
if (!root) {
return 0;
}
if (!root->left && !root->right) {
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;
}
return 0;
}
int main() {
char expression[100];
printf("Enter the expression: ");
scanf("%s", expression);
TreeNode *root = buildExpressionTree(expression);
int result = evaluateExpressionTree(root);
printf("Result: %d\n", result);
return 0;
}
```
这个程序首先实现了一个栈和栈相关的操作函数,用于在转换中缀表达式为表达式树时辅助操作。然后,使用一个函数 `buildExpressionTree` 将中缀表达式转换为表达式树。最后,使用另一个函数 `evaluateExpressionTree` 对表达式树进行递归求值。
阅读全文