解题思路:利用递归的思想,遍历整棵树。看代码即可理解,注意下一注释。
题目大意:
将多叉树转化为括号表示法。每个节点用字母表示,每个非叶节点总下方会有一个”|“字符,然后下方是一排”-“字符,恰好覆盖所有子节点的上方。单独的一行”#“为数据结束标记。
Sample Professor’s Trees Corresponding Our Trees
2 A | -------- B C D | | ----- - E F G # e | ---- f g #
| (A(B()C(E()F())D(G()))) (e(f()g()))
|
#include<cstdio>
#include<cstring>
#include<string>
#include<iostream>
#include<cctype>
using namespace std;
string a[100];
int n;
void DFS(int x,int y) //递归处理
{
cout<<a[x][y];
if(x==n-1) //到了末行打印括号直接返回
{
cout<<"()";
return;
}
if(a[x+1][y]=='|')
{
int st=y,end=y;
while(a[x+2][st]!=' ')
{
if(st==0) //一定注意加上该判断,等于0再自减数组会越界出错
{
st--;
break;
}
st--;
}
st++;
while(a[x+2][end]!=' ')
{
if(end==a[x+2].length()-1) //同样,不做判断数组会越界
{
end++;
break;
}
end++;
}
end--;
cout<<"(";
for(int i=st;i<=end;i++)
{
if(isalpha(a[x+3][i]))
{
DFS(x+3,i);
}
}
cout<<")";
}
if(a[x+1][y]==' ')
{
cout<<"()";
}
}
int main()
{
int T;
getline(cin,a[0]); //这里不要直接cin>>T;有个回车会被后面的getline补捉导致出错
T=a[0][0]-'0';
while(T--)
{
n=0;
while(getline(cin,a[n]))
{
if(a[n][0]=='#')
break;
n++;
}
for(int i=0;i<a[0].length();i++)
{
if(isalpha(a[0][i]))
{
cout<<"(";
DFS(0,i);
cout<<")";
}
}
cout<<endl;
}
return 0;
}