输入简单算术表达式,利用二叉树表示,并在创建表达式树后求表达式的值C语言
时间: 2023-12-15 19:05:25 浏览: 79
利用二叉树求表达式值
好的,以下是示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.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;
}
Node* createExpressionTree(char* expression, int start, int end) {
if (start > end) {
return NULL;
}
Node* root = createNode(expression[start]);
int index = -1;
int parentheses = 0;
for (int i = start + 1; i <= end; i++) {
if (expression[i] == '(') {
parentheses++;
} else if (expression[i] == ')') {
parentheses--;
}
if (parentheses == 0 && (expression[i] == '+' || expression[i] == '-'
|| expression[i] == '*' || expression[i] == '/')) {
index = i;
break;
}
}
if (index != -1) {
root->left = createExpressionTree(expression, start + 2, index - 1);
root->right = createExpressionTree(expression, index + 2, end - 1);
}
return root;
}
int evaluateExpressionTree(Node* root) {
if (root == NULL) {
return 0;
}
if (isdigit(root->data)) {
return root->data - '0';
}
int left = evaluateExpressionTree(root->left);
int right = evaluateExpressionTree(root->right);
switch (root->data) {
case '+':
return left + right;
case '-':
return left - right;
case '*':
return left * right;
case '/':
return left / right;
default:
return 0;
}
}
int main() {
char expression[100];
printf("请输入算术表达式:");
scanf("%s", expression);
int len = strlen(expression);
Node* root = createExpressionTree(expression, 0, len - 1);
int result = evaluateExpressionTree(root);
printf("表达式的值为:%d", result);
return 0;
}
```
输入格式为不带空格的算术表达式,例如:2+3*4-5/2。输出结果为表达式的值。
阅读全文