晴神模拟赛

你们要的中缀表达式树

Case Time Limit: 100 MS (Others) / 200 MS (Java) Case Memory Limit: 256 MB (Others) / 512 MB (Java)
Accepted: 74 Total Submission: 280

Problem Description

给定一棵二叉树,二叉树的各个结点要么表示四则运算符+、-、、/,要么表示一个不超过10的非负整数。将这棵二叉树看作中缀表达式树,输出对应的中缀表达式,以及该中缀表达式的计算结果。

注意,输出的中缀表达式中,除了最外层以外,内层的每个“左操作数 操作符 右操作数”形式的两侧都要加上一对小括号。例如2+(3(4/5))就是一个可能的正确输出。

Input

每个输入文件中一组数据。

第一行一个正整数N(N<=30),代表二叉树的结点个数(结点编号为0到N-1)。

第二行按结点编号从小到大的顺序给出N个结点的值(用空格隔开),其要么是四则运算符+、-、*、/的其中一个,要么是一个不超过10的非负整数。

接下来按结点编号从小到大的顺序给出N行,每行为两个编号,分别代表该结点的左孩子编号和右孩子编号,如果不存在左(右)孩子,那么就用字符’-'代替。数据保证编号在0到N-1之间,且中缀表达式树一定是合法的。

Output

输出一行,即所求的中缀表达式与对应的计算结果(精度保留两位小数),表达式与计算结果之间用空格隔开。注意输出的中缀表达式中不允许有空格。数据保证中缀表达式合法,且计算过程中不会出现除数为0的情况。

Sample Input

5

  • 3 + 4 6
    1 2

3 4

Sample Output

3*(4+6) 30.00

2017

#include
#include
#include
using namespace std;
const int maxn = 1e2;
struct node{
    string data;
    int left;
    int right;
}a[maxn];
string save[maxn] ;
int  num;

int Dfs(int n, int depth){

    int tempa, tempb;
    if(a[n].left != -1 && a[n].right != -1 &&depth != 0) cout << "(";
    if(a[n].left != -1){
        tempa = Dfs(a[n].left, depth + 1);
    }
    cout << a[n].data;
    if(a[n].right != -1){
        tempb = Dfs(a[n].right, depth + 1);
    }
    if(a[n].left != -1 && a[n].right != -1 &&depth != 0) cout << "(";
    if(a[n].left != -1 && a[n].right != -1){
        if(a[n].data == "*") return tempa * tempb;
        if(a[n].data == "+") return tempa + tempb;
        if(a[n].data == "-") return tempa - tempb;
        if(a[n].data == "/") return tempa / tempb;
    }else return stoi(a[n].data);
}
int main()
{
    int i, j ;
    string  tempa, tempb;
    cin >> num;
    for(i = 0; i > save[i];
    }
    for(i = 0; i < num; i++){
        cin >>tempa >> tempb;
        if(tempa == "-"){
            a[i].left = -1;
        }else a[i].left = stoi(tempa);
        if(tempb == "-"){
            a[i].right = -1;
        }else a[i].right = stoi(tempb);
        a[i].data = save[i];
    }
    int sum =  Dfs(0, 0);
    cout <<""<

你可能感兴趣的:(PAT-A)