【数据结构】中缀表达式构造二叉树转换成后缀表达式

本文介绍了一个使用 C 语言实现的程序,该程序通过构建表达式树来解析数学表达式3*4+5-2/1。文章详细展示了如何使用栈来辅助构造表达式树,并提供了完整的源代码及展示如何遍历这棵树以输出表达式的具体过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include "stdio.h"  
#include "string.h"  
#include "stdlib.h"  
#include "stack"  
using namespace std;  
  
const char str[] = "3*4+5-2/1";  
  
struct tree  
{  
    char c;  
    struct tree* left;  
    struct tree* right;  
};  
stack<struct tree*> subTreeStack;  
stack<char> operatorStack;  
  
  
struct tree*  BuildTree()  
{   
  
    struct tree* node;  
    for (unsigned int pos = 0; pos < strlen(str); pos++)  
    {  
        if (str[pos] - '0' >= 0 && str[pos] - '0' <= 9)    //若是数字则作为叶子节点  
        {  
  
            node = (struct tree*) malloc(sizeof(struct tree));  
            node->c = str[pos];  
            node->left = NULL;  
            node->right = NULL;  
              
          
              
            subTreeStack.push(node);  
        }  
        else if (str[pos] == '*' || str[pos] == '/' || str[pos] == '+' || str[pos] == '-')  
        {  
            if (!operatorStack.empty() && (str[pos] == '+' || str[pos] == '-'))  //若优先级比栈顶元素低  
            {  
                node = (struct tree*) malloc(sizeof(struct tree));  
                node->c = operatorStack.top();  
                node->right = subTreeStack.top();  
                subTreeStack.pop();  
                node->left = subTreeStack.top();  
                subTreeStack.pop();  
                  
                subTreeStack.push(node);  
              
  
                operatorStack.pop();  
                operatorStack.push(str[pos]);  
            }  
            else  
                operatorStack.push(str[pos]);  
        }  
      
      
    }  
      
      
    while(!operatorStack.empty())  
    {  
      
        node = (struct tree*) malloc(sizeof(struct tree));  
        node->c = operatorStack.top();  
        operatorStack.pop();  
        node->right = subTreeStack.top();  
        subTreeStack.pop();  
        node->left = subTreeStack.top();  
        subTreeStack.pop();  
          
        subTreeStack.push(node);  
      
    }  
    return subTreeStack.top();  
  
}  
void PrintTree(struct tree* node)  
{  
    if (node == NULL)  
        return;  
    PrintTree(node->left);  
    printf("%c", node->c);  
    PrintTree(node->right);  
}  
  
  
void main()  
{  
    struct tree* root = BuildTree();  
    PrintTree(root);  
}  

数据结构中,将中缀表达式转换为二叉树并求解是一个常见的操作。中缀表达式是我们日常使用的数学表达式,如 `(A + B) * (C - D)`。而二叉树是一种数据结构,每个节点最多有两个子节点。 以下是中缀表达式转换为二叉树并求解的基本步骤: 1. **中缀表达式后缀表达式(逆波兰表达式)**: - 使用栈来处理操作符。 - 遍历中缀表达式,如果是操作数,直接输出。 - 如果是左括号 `(`,压入栈。 - 如果是右括号 `)`,弹出栈中元素直到遇到左括号 `(`。 - 如果是操作符,比较其与栈顶操作符的优先级,如果栈顶操作符优先级高,则弹出栈顶操作符并输出,然后继续比较。 - 最后,将栈中剩余的操作符依次弹出并输出。 2. **后缀表达式二叉树**: - 使用栈来构建二叉树。 - 遍历后缀表达式,如果是操作数,创建一个节点并压入栈。 - 如果是操作符,弹出栈顶的两个节点,将它们作为当前操作符节点的左右子节点,然后将当前节点压入栈。 3. **二叉树求解**: - 遍历二叉树,如果是操作符节点,递归求解其左右子节点,并根据操作符进行计算。 - 如果是操作数节点,直接返回其值。 以下是一个简单的C语言示例代码,展示了如何将中缀表达式转换为二叉树并进行求解: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> // 定义二叉树节点 typedef struct TreeNode { char data; struct TreeNode* left; struct TreeNode* right; } TreeNode; // 创建新节点 TreeNode* createNode(char data) { TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode)); node->data = data; node->left = node->right = NULL; return node; } // 判断字符是否为操作符 int isOperator(char c) { return c == '+' || c == '-' || c == '*' || c == '/'; } // 中缀表达式后缀表达式 void infixToPostfix(char* infix, char* postfix) { char stack[100]; int top = -1; int i = 0, j = 0; while (infix[i] != '\0') { if (isdigit(infix[i]) || isalpha(infix[i])) { postfix[j++] = infix[i]; } else if (infix[i] == '(') { stack[++top] = infix[i]; } else if (infix[i] == ')') { while (top != -1 && stack[top] != '(') { postfix[j++] = stack[top--]; } top--; } else { while (top != -1 && stack[top] != '(' && ((stack[top] == '*' || stack[top] == '/') && (infix[i] == '+' || infix[i] == '-'))) { postfix[j++] = stack[top--]; } stack[++top] = infix[i]; } i++; } while (top != -1) { postfix[j++] = stack[top--]; } postfix[j] = '\0'; } // 后缀表达式二叉树 TreeNode* postfixToTree(char* postfix) { TreeNode* stack[100]; int top = -1; for (int i = 0; postfix[i] != '\0'; i++) { if (isalnum(postfix[i])) { stack[++top] = createNode(postfix[i]); } else { TreeNode* right = stack[top--]; TreeNode* left = stack[top--]; TreeNode* node = createNode(postfix[i]); node->left = left; node->right = right; stack[++top] = node; } } return stack[top]; } // 二叉树求解 int evaluate(TreeNode* root) { if (root == NULL) return 0; if (!isOperator(root->data)) return root->data - '0'; int leftVal = evaluate(root->left); int rightVal = evaluate(root->right); switch (root->data) { case '+': return leftVal + rightVal; case '-': return leftVal - rightVal; case '*': return leftVal * rightVal; case '/': return leftVal / rightVal; } return 0; } // 打印二叉树 void printTree(TreeNode* root) { if (root == NULL) return; printTree(root->left); printf("%c ", root->data); printTree(root->right); } int main() { char infix[] = "(3+5)*(4-2)"; char postfix[100]; infixToPostfix(infix, postfix); printf("Postfix: %s\n", postfix); TreeNode* root = postfixToTree(postfix); printf("Infix: "); printTree(root); printf("\n"); int result = evaluate(root); printf("Result: %d\n", result); return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值