思路:
1. 中序遍历该树;
2. 若该结点不是根结点并且不是叶子结点,则需要在其遍历左子树前添加左括号,在遍历完右子树后添加右括号。
代码:
#include<iostream>
#include<cstdio>
using namespace std;
const int N = 25;
int n;
int root = 0;
int vis[N];
struct Node
{
string data;
int l, r;
}a[N];
void dfs(int u)
{
//该结点不是根节点或者叶子结点则需要加括号
if(u != root && (a[u].l != -1 || a[u].r != -1)) cout << "(";
if(a[u].l != -1) dfs(a[u].l);
cout << a[u].data;
if(a[u].r != -1) dfs(a[u].r);
if(u != root && (a[u].l != -1 || a[u].r != -1)) cout << ")";
}
int main()
{
cin >> n;
for(int i = 1; i <= n; i++)
{
cin >> a[i].data >> a[i].l >> a[i].r;
if(a[i].l != -1) vis[a[i].l] = 1;
if(a[i].r != -1) vis[a[i].r] = 1;
}
for(int i = 1; i <= n; i++)
{
if(!vis[i])
{
root = i;
break;
}
}
dfs(root);
return 0;
}