数据结构与算法实验 实验7:算术表达式的语义二叉树 (表达式二叉树转化为中缀表达式,求值)

一个算术表达式的计算语义可以用二叉树唯一的表示出来。假设算术表达式的语义二叉树已经给出,请编码实现算术表达式的中缀形式(保持计算语义)的输出,并计算出该表达式的值。

要求:

1)使用二叉树的完全前序序列建立表达式的语义二叉树,空子树用符号@表示;

2)算术运算符包括:+, -, *, / ; 运算量只考虑单数字字符(1位整数)

3 ) 输出时用括号该表优先级;

提示:

1)递归执行下列步骤即可求值:先分别求出左子树和右子树表示的子表达式的值,最后根据根结点的运算符的要求,计算出表达式的最后结果。

2)二叉树的中序遍历序列与原算术表达式基本相同,但是需要将中序序列加上括号,即当根结点运算符优先级高于左子树(或右子树)根结点运算符时,就需要加括号。

例如:

输入:*2@@-3@@1@@

输出:2*(3-1)=4

例如:

输入:
*2@@-3@@1@@
Result:
2*(3-1)=4

思路
1)输出表达式:
依题目要求先由完全先序序列建树,然后通过中序遍历输出中缀表达式,难点是判断什么时候输出括号,当根节点的优先级大于其儿子节点的优先级时需要输出括号,但是注意若是根节点是’-’,左子树无论是什么符号都不用输出括号。否则会出现(5+6)-(7+8)的情况(详见下面用例)
2)求值:
直接由树的后序遍历可以得到后缀表达式,然后就可以直接根据后缀表达式求值。

测试用例

/+1@@/3@@4@@-+5@@6@@+7@@8@@
(1+3/4)/(5+6-(7+8))=-0.4375
*+1@@/3@@4@@-+5@@6@@+7@@8@@
(1+3/4)*(5+6-(7+8))=-7
-+1@@/3@@4@@-+5@@6@@+7@@8@@
1+3/4-(5+6-(7+8))=5.75
+-*1@@2@@-3@@4@@/+5@@6@@*7@@8@@
1*2-(3-4)+(5+6)/(7*8)=3.19643
-2@@-+2@@1@@1@@
2-(2+1-1)=0
#include <iostream>
#include <cstdio>
#include <queue>
#include <stack>
#include <cstring>
#include <cstdlib>
using namespace std;

struct node
{
    char x;
    node* lson;
    node* rson;
};

void creat(node* &root)///完全先序序列建树
{
    root=new node;
    char c;
    cin>>c;
    if(c=='@') root=NULL;
    else
    {
        root->x=c;
        creat(root->lson);
        creat(root->rson);
    }
}

bool judge(char c)///判断是否为运算符
{
    if(c=='*'||c=='/'||c=='-'||c=='+')return true;
    return false;
}

bool check(char op1,char op2,int lr)///判断优先级,增添子树判断
{
    if(lr==1&&op2=='-') ///若为左子树,且其父亲为'-',则其优先级一定大于父亲的优先级,不需要加()
    return false;
    if((op1=='+'||op1=='-')&&(op2=='*'||op2=='/'||op2=='-'))
        return true;
    if((op1=='*'&&op2=='/')||(op1=='/'&&op2=='/'))
        return true;
    return false;
}

int cnt=0;
char str[1000];
void print(node *root,char op,int lr)///op为其双亲节点的符号,lr为左右子树的判断标准,
{
    if(root==NULL)  return;
    if(judge(root->x)&&check(root->x,op,lr))///根的优先级大,输出'('
    	cout<<'(';
    print(root->lson,root->x,1);///左子树递归
    cout<<root->x;///输出中缀表达式
    print(root->rson,root->x,2);///右子树递归
    if(judge(root->x)&&check(root->x,op,lr))///根的优先级大,输出')'
    	cout<<')';
    str[cnt++]=root->x;///获取后缀表达式

}

double cal(char op,double num1,double num)///计算
{
    if(op=='+') return num1+num;
    if(op=='-') return num1-num;
    if(op=='*') return num1*num;
    if(op=='/') return num1/num;
}

stack<double> sta;
void getans()///后续表达式求值,利用栈计算
{
    int len=strlen(str);
    for(int i=0;i<len;i++)
    {
        if(isdigit(str[i]))
            sta.push(str[i]-'0');
        else
        {
            if(!sta.empty())
            {
                double temp1=sta.top();
                sta.pop();
                double temp2=sta.top();
                sta.pop();
                sta.push(cal(str[i],temp2,temp1));
            }
        }
    }

}

int main()
{
    node *root;
    creat(root);
    print(root,'.',0);
    cout<<'=';
    getans();
    printf("%.5lf\n",sta.top());
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章