表达式树的值

表达式树的创建与输出在上一篇中,下面就利用表达式树来递归计算多项式


#include<bits/stdc++.h>
using namespace std;
string s;
typedef struct node
{
    int data;
    struct node *lc,*rc;
} node,*link;
void creat(link &L)
{
    cin>>s;
    if(s[0]=='#')
        L=NULL;
    else
    {
        int p=0;
        if(s[0]=='+')
            p=-1;
        else if(s[0]=='-')
            p=-2;
        else if(s[0]=='*')
            p=-3;
        else if(s[0]=='/')
            p=-4;
        else
        {
            int i=0,n=s.size();
            while(i<n)
            {
                p=p*10+(s[i]-'0');
                i++;
            }
        }
        L=new node;
        L->data=p;
        creat(L->lc);
        creat(L->rc);
    }
}
void print(link L)
{
    if(L)
    {
        if(L->data>=0) printf("%d",L->data);
        else
        {
            printf("(");
            print(L->lc);
            if(L->data==-1) printf("+");
            else if(L->data==-2) printf("-");
            else if(L->data==-3) printf("*");
            else printf("/");
            print(L->rc);
            printf(")");
        }
    }
}
int js(link L)
{
    if(L)
    {
        if(L->data>=0) return L->data;
        if(L->data==-1) return js(L->lc)+js(L->rc);
        else if(L->data==-2) return js(L->lc)-js(L->rc);
        else if(L->data==-3) return js(L->lc)*js(L->rc);
        else return js(L->lc)/js(L->rc);
    }
}
int main()
{
    while(cin>>s)
    {
        link L;
        int p=0;
        if(s[0]=='+')
            p=-1;
        else if(s[0]=='-')
            p=-2;
        else if(s[0]=='*')
            p=-3;
        else if(s[0]=='/')
            p=-4;
        else
        {
            int i=0,n=s.size();
            while(i<n)
            {
                p=p*10+(s[i]-'0');
                i++;
            }
        }
        L=new node;
        L->data=p;
        creat(L->lc);
        creat(L->rc);
        print(L);
        printf("=");
        printf("%d\n",js(L));
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41061455/article/details/80564663