跳到正文

个人记录

表达式树

cmwqf约 2 分钟
原文
文章信息与版本

文章信息

发布
2018年4月30日
收录
2025年12月12日
更新
2026年11月18日
篇幅
约 2 分钟

版本

  1. v2当前
  2. v1
C++
//找到最后计算的运算符(整棵树的根),然后递归处理。
#include<cstdio>
#include<cstring>
using namespace std;
const int maxN=1000;
struct Node
{
    int lch,rch;
    char op;
}tree[maxN+1];//每个节点的左右子节点编号 ,每个节点的字符
int nc=0;//节点数
int build_tree(char *s,int x,int y)//x指当前字符串第一个字符的位置,y指最后一个字符的后面一位
{
    int c1=-1,c2=-1,p=0;
    int u;
    if(y-x==1)//只有一个字符,建立单独节点
    {
        u=++nc;
        tree[u].lch=tree[u].rch=0;tree[u].op=s[x];
        return u;
    }
    for(int i=x;i<y;i++)
    {
        switch(s[i])
        {
            case '(':p++;break;
            case ')':p--;break;//相当于一个栈,当'('和')'匹配时p=0
            case '+':
            case '-':if(!p) c1=i;break;
            case '*':
            case '/':if(!p) c2=i;break;//只有在括号外面的符号才可能是最后计算的;
        }
        //而*和/的优先级比+和-高,所以优先选择+,-
    }
    if(c1<0) c1=c2;//找不到括号外的加减号,就用乘除号
    if(c1<0)
       return build_tree(s, x+1, y-1);//说明整个表达式用括号括起来了,要去掉括号
    u=++nc;
    tree[u].lch=build_tree(s, x, c1);
    tree[u].rch=build_tree(s, c1+1, y);
    tree[u].op=s[c1];
    return u;
}
int main()
{
    char s[maxN+1];
    scanf("%s",s);
    int len=strlen(s);
    build_tree(s, 0, len);
    for(int i=1;i<=nc;i++) printf("%d %d %d %c\n",i,tree[i].lch,tree[i].rch,tree[i].op);
    return 0;
}
//a+b*(c-d)-e/f
原文