很水的题,建树,按要求输出即可
#include<iostream>
#include<string>
using namespace std;
struct node {
string data;
int l, r;
};
node all[25];
int root;
void InOrderTraver(int index)
{
int flag = 0;
if ((all[index].l == -1 && all[index].r == -1)||index==root) flag = 1;
if (flag != 1) printf("(");
if (all[index].l != -1) InOrderTraver(all[index].l);
printf("%s", all[index].data.c_str());
if (all[index].r != -1) InOrderTraver(all[index].r);
if (flag != 1) printf(")");
}
int main()
{
int visited[25] = {0};
int N;
cin >> N;
for (int t = 1;t <= N;t++)
{
cin >> all[t].data >> all[t].l >> all[t].r;
if (all[t].l != -1)visited[all[t].l]++;
if (all[t].r != -1)visited[all[t].r]++;
}
for(int t=1;t<=N;t++)
if (visited[t] == 0) {
root = t;
break;
}
InOrderTraver(root);
cout << endl;
}