使用C语言建立一个表达式树,仅适用于十进制的加减乘除四则运算,参考结构: typedef struct ExpressionTree{ int element; ExpressionTree* left_tree; ExpressionTree* right_tree; }ExpressionTree, *ExpressionTreeRoot; 包含以下数据操作: int evaluate(ExpressionTreeRoot &T); //获得整个表达式树或者相关子树的计算结果; void in_fix( int, bool ); //以中缀方式打印表达式; void reverse_polish(); //以后缀方式打印表达式; bool is_leaf(); //判断节点是否为叶子节点;缀方式打印表达式; bool is_leaf(); //判断节点是否为叶子节点;
时间: 2024-02-21 17:00:46 浏览: 59
好的,这是您的问题。以下是使用C语言建立一个表达式树并实现相关操作的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
//定义表达式树节点结构体
typedef struct ExpressionTree {
int element;
struct ExpressionTree* left_tree;
struct ExpressionTree* right_tree;
} ExpressionTree, *ExpressionTreeRoot;
//创建表达式树
ExpressionTreeRoot create_expression_tree(char* expression, int start, int end) {
if (start == end) { //只有一个数字
ExpressionTreeRoot node = (ExpressionTreeRoot)malloc(sizeof(ExpressionTree));
node->element = expression[start] - '0';
node->left_tree = node->right_tree = NULL;
return node;
}
//找到最后一个运算符的位置
int pos = end;
int bracket_count = 0;
for (int i = end; i >= start; i--) {
if (expression[i] == ')') bracket_count++;
if (expression[i] == '(') bracket_count--;
if (bracket_count == 0 && (expression[i] == '+' || expression[i] == '-' || expression[i] == '*' || expression[i] == '/')) {
pos = i;
break;
}
}
ExpressionTreeRoot node = (ExpressionTreeRoot)malloc(sizeof(ExpressionTree));
node->element = expression[pos];
//递归建立左右子树
node->left_tree = create_expression_tree(expression, start, pos - 1);
node->right_tree = create_expression_tree(expression, pos + 1, end);
return node;
}
//计算表达式树的值
int evaluate(ExpressionTreeRoot T) {
if (T->left_tree == NULL && T->right_tree == NULL) { //叶子节点
return T->element - '0';
}
int left = evaluate(T->left_tree);
int right = evaluate(T->right_tree);
switch (T->element) {
case '+': return left + right;
case '-': return left - right;
case '*': return left * right;
case '/': return left / right;
}
return 0;
}
//以中缀方式打印表达式
void in_fix(ExpressionTreeRoot T, bool is_root) {
if (T == NULL) return;
if (!is_leaf(T) && !is_root) putchar('(');
in_fix(T->left_tree, false);
printf("%c", T->element);
in_fix(T->right_tree, false);
if (!is_leaf(T) && !is_root) putchar(')');
}
//以后缀方式打印表达式
void reverse_polish(ExpressionTreeRoot T) {
if (T == NULL) return;
reverse_polish(T->left_tree);
reverse_polish(T->right_tree);
printf("%c ", T->element);
}
//判断节点是否为叶子节点
bool is_leaf(ExpressionTreeRoot T) {
return (T->left_tree == NULL && T->right_tree == NULL);
}
int main() {
char* expression = "5*(3+4)-2/2";
ExpressionTreeRoot T = create_expression_tree(expression, 0, strlen(expression) - 1);
printf("中缀表达式:");
in_fix(T, true);
printf("\n后缀表达式:");
reverse_polish(T);
printf("\n计算结果:%d\n", evaluate(T));
return 0;
}
```
希望对您有所帮助!
阅读全文