题目地址

Given a syntax tree (binary), you are supposed to output the corresponding infix expression, with parentheses reflecting the precedences of the operators.

Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤ 20) which is the total number of nodes in the syntax tree. Then N lines follow, each gives the information of a node (the i-th line corresponds to the i-th node) in the format:

data left_child right_child

where data is a string of no more than 10 characters, left_child and right_child are the indices of this node's left and right children, respectively. The nodes are indexed from 1 to N. The NULL link is represented by −1. The figures 1 and 2 correspond to the samples 1 and 2, respectively.

infix1.JPG infix2.JPG
Figure 1 Figure 2
Output Specification:
For each case, print in a line the infix expression, with parentheses reflecting the precedences of the operators. Note that there must be no extra parentheses for the final expression, as is shown by the samples. There must be no space between any symbols.

Sample Input 1:
8

  • 8 7
  1. -1 -1
  • 4 1
  • 2 5
  1. -1 -1

d -1 -1

  • -1 6
  1. -1 -1

Sample Output 1:
(a+b)(c(-d))

Sample Input 2:
8
2.35 -1 -1

  • 6 1
  • -1 4
    % 7 8
  • 2 3
  1. -1 -1

str -1 -1
871 -1 -1

Sample Output 2:
(a*2.35)+(-(str%871))

#include <cstdio>
#include <cstring>
#include<iostream>
#include <vector>
#include<math.h>
#include<string>
#include<queue>
#include <algorithm>
#include<set>
#include<map>
using namespace std;
const int maxn=1010;
struct node{
    string data;            //中缀表达式的判断性主要all lchild;has r and no l;has no child;
    int lchild,rchild;
}s[maxn];
int n,root=-1;
bool not_root[maxn]={0};
string dfs(int idx){
    if(s[idx].lchild!=-1&&s[idx].rchild!=-1) return "("+dfs(s[idx].lchild)+s[idx].data+dfs(s[idx].rchild)+")";
    else if(s[idx].lchild==-1&&s[idx].rchild!=-1) return "("+s[idx].data+dfs(s[idx].rchild)+")";
    else if(s[idx].lchild==-1&&s[idx].rchild==-1) return s[idx].data;
}
// void dfs(int idx){               //仅在非跟的有子结点时输出括号,进行中序遍历
//     if(idx==-1) return;
//     if(idx!=root&&(s[idx].lchild!=-1||s[idx].rchild!=-1)) cout<<"(";
//     dfs(s[idx].lchild);
//     cout<<s[idx].data;
//     dfs(s[idx].rchild);
//     if(idx!=root&&(s[idx].lchild!=-1||s[idx].rchild!=-1)) cout<<")";
// }
int main(){
    cin>>n;
    for(int i=1;i<=n;i++) {
        cin>>s[i].data>>s[i].lchild>>s[i].rchild;
        if(s[i].lchild!=-1)    not_root[s[i].lchild]=1;if(s[i].rchild!=-1)    not_root[s[i].rchild]=1;
    }
    for(int i=1;i<=n;i++) if(!not_root[i]){
        root=i;break;
    }
    string ans=dfs(root);
    if(ans[0]=='('&&ans[ans.length()-1]==')'){          //这里最重要;
        ans.erase(0,1);
        ans.erase(ans.end()-1);
    }
    cout<<ans;
}