表达式树

来源:互联网 发布:js文件在线格式化 编辑:程序博客网 时间:2024/05/18 03:21

问题描述:《算法竞赛入门经典2 p353》
将一个表达式如(a+b*(c-d)-e/f)表示成一个二叉树。即给出中序序列求二叉树。
分析:
找出最后计算的运算符,它是整个树的根,然后递归处理;
找出最后计算的运算符:最后计算的运算符一定在括号外,并且当括号外有+-时一定为最右边一个+-运算符,如果没有+-,则一定是最右边的一个*/运算符。
代码:

#include <iostream>#include <cstring>#include <string>#include <stdio.h>#include <queue>using namespace std;const int maxn = 1000;int lch[maxn],rch[maxn];char op[maxn];int nc=0;int build_tree(char * s, int x, int y);void print(int u);int main(){    char s[1000];    scanf("%s",s);    int L=strlen(s);    int u=build_tree(s,0,L);    print(u);    return 0;}int build_tree(char * s, int x, int y){    int i,c1=-1,c2=-1,p=0,u;    if(y-x==1)    {        u=++nc;        lch[u]=0;        rch[u]=0;        op[u]=s[x];        return u;    }    for(i=x;i<y;i++)    {        switch(s[i])        {            case '(':p++;break;            case ')':p--;break;            case '+':            case '-':if(!p) c1=i;break;            case '*':            case '/':if(!p) c2=i;break;            default : break;        }    }    if(c1<0) c1=c2;    if(c1<0) return build_tree(s,x+1,y-1);    u=++nc;    lch[u]=build_tree(s,x,c1);    rch[u]=build_tree(s,c1+1,y);    op[u]=s[c1];    return u;}void print(int u){    /*    //先序序列   cout<<op[u];   if(lch[u]>0) print(lch[u]);   if(rch[u]>0) print(rch[u]);    */    //层次遍历:    queue<int> q;    int t;    while(!q.empty())    {        q.pop();    }    q.push(u);    while(!q.empty())    {        t=q.front();        q.pop();        cout<<op[t];        if(lch[t]>0)            q.push(lch[t]);        if(rch[t]>0)            q.push(rch[t]);    }}
1 0