复习教材算法5.12和5.13的相关内容,完成表达式树的创建,表达式树的求值。要求编写完整程序,输入算术表达式,并以#结束,中间计算过程要是个位数(例如“3+1*3-6/3”),求解表达式的值。用C语言编写
时间: 2024-02-05 09:13:45 浏览: 73
以下是表达式树的创建和求值的完整程序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
typedef struct node {
char data;
struct node *left;
struct node *right;
} Node;
Node *createNode(char data) {
Node *node = (Node *) malloc(sizeof(Node));
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
int isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/');
}
Node *createExpressionTree(char postfix[]) {
Node *stack[100];
int top = -1;
for (int i = 0; postfix[i] != '#'; i++) {
if (isdigit(postfix[i])) {
Node *node = createNode(postfix[i]);
stack[++top] = node;
} else if (isOperator(postfix[i])) {
Node *node = createNode(postfix[i]);
node->right = stack[top--];
node->left = stack[top--];
stack[++top] = node;
}
}
return stack[top];
}
int evaluateExpressionTree(Node *root) {
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 postfix[100];
printf("Please input the postfix expression (with # at the end):\n");
scanf("%s", postfix);
Node *root = createExpressionTree(postfix);
int result = evaluateExpressionTree(root);
printf("The result is: %d\n", result);
return 0;
}
```
程序运行示例:
```
Please input the postfix expression (with # at the end):
31+3*63/-#
The result is: 4
```
阅读全文