题目来源
https://pintia.cn/problem-sets/994805342720868352/problems/994805347921805312
分析
详解:https://www.liuchuo.net/archives/3798
本站类似题目(方法一样):https://blog.csdn.net/allisonshing/article/details/100642958
陷阱
题目说最后结果外面不要有括号。
Note that there must be no extra parentheses for the final expression, as is shown by the samples.
满分代码
#include<iostream>
using namespace std;
struct node{
string data;
int l,r;
}a[30];
string dfs(int r){
if(r==-1)return "";
if(a[r].l==-1&&a[r].r!=-1)return "("+a[r].data+dfs(a[r].r)+")";
if(a[r].l!=-1&&a[r].r!=-1)return "("+dfs(a[r].l)+a[r].data+dfs(a[r].r)+")";
return a[r].data;
}
int main(){
int n,have[100] = {0},root = 1;
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i].data>>a[i].l>>a[i].r;
if(a[i].l != -1) have[a[i].l] = 1;
if(a[i].r != -1) have[a[i].r] = 1;
}
while(have[root] == 1) root++;
string ans = dfs(root);
if(ans[0] == '(') ans = ans.substr(1,ans.size()-2);
cout << ans;
return 0;
}