表达式二叉树函数(C实现,实现了通过前缀,中缀,后缀表达式构建二叉树)
时间: 2024-02-01 11:03:46 浏览: 135
用二叉树实现中缀表达式转换成后缀表达式
5星 · 资源好评率100%
以下是一个简单的实现,实现了通过后缀表达式构建二叉树:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_EXPR_LEN 100
typedef struct TreeNode {
char val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
typedef struct StackNode {
TreeNode *val;
struct StackNode *next;
} StackNode;
typedef struct Stack {
StackNode *top;
} Stack;
Stack* createStack() {
Stack *s = (Stack*) malloc(sizeof(Stack));
s->top = NULL;
return s;
}
void push(Stack *s, TreeNode *val) {
StackNode *n = (StackNode*) malloc(sizeof(StackNode));
n->val = val;
n->next = s->top;
s->top = n;
}
TreeNode* pop(Stack *s) {
if (s->top == NULL) {
return NULL;
}
TreeNode *val = s->top->val;
StackNode *temp = s->top;
s->top = s->top->next;
free(temp);
return val;
}
TreeNode* buildExprTree(char *expr) {
Stack *s = createStack();
int len = strlen(expr);
for (int i = 0; i < len; i++) {
char c = expr[i];
if (isdigit(c)) {
TreeNode *n = (TreeNode*) malloc(sizeof(TreeNode));
n->val = c;
n->left = NULL;
n->right = NULL;
push(s, n);
} else {
TreeNode *n = (TreeNode*) malloc(sizeof(TreeNode));
n->val = c;
n->right = pop(s);
n->left = pop(s);
push(s, n);
}
}
TreeNode *root = pop(s);
free(s);
return root;
}
void inOrderTraversal(TreeNode *root) {
if (root == NULL) {
return;
}
inOrderTraversal(root->left);
printf("%c ", root->val);
inOrderTraversal(root->right);
}
int main() {
char expr[MAX_EXPR_LEN];
printf("请输入后缀表达式:");
scanf("%s", expr);
TreeNode *root = buildExprTree(expr);
printf("中序遍历结果:");
inOrderTraversal(root);
printf("\n");
return 0;
}
```
这段代码通过一个栈来辅助构建表达式二叉树,对于每个字符,如果是数字则创建一个只包含该数字的叶子节点,如果是运算符则创建一个新的节点,并将栈顶的两个节点分别作为左右子树连接到该节点上,然后将该节点压入栈中。最后,栈中仅剩的一个节点就是构建好的表达式二叉树的根节点。
阅读全文