题目链接
题目大意:
根据题目给的树按照题目输出要求输出先序遍历
分析:
用一个字符串数组将输入存储起来。然后递归输出即可。
有一个巨坑,结点不能为‘#’,但题目说可以。
#include <bits/stdc++.h>
using namespace std;
const int maxn = 200+10;
string buf[maxn];
int cnt;
void dfs(int n, int m) {
cout << buf[n][m] << "(";
if(n+1<cnt && buf[n+1][m]=='|') { //有子树
int begin = m, end = m;
while(buf[n+2][begin]=='-' && begin>0)
begin--;
if(begin) begin++;
while(buf[n+2][end]=='-' && end<buf[n+2].length())
end++;
for(int i = begin; i < end && i<buf[n+3].length(); i++) {
if(buf[n+3][i]!=' ' && buf[n+3][i]!='#')
dfs(n+3,i);
}
}
cout << ")";
}
void solve() {
if(buf[0]=="#") { cout << "()" << endl; return; }
cout << "(";
for(int i = 0; i < buf[0].length(); i++)
if(buf[0][i]!=' ') dfs(0,i);
cout << ")" << endl;
}
int main() {
freopen("i.txt","r",stdin);
freopen("o.txt","w",stdout);
int n;
cin >> n;
getchar();
while(n--) {
cnt = 0;
while(true) {
getline(cin, buf[cnt]);
if(buf[cnt]!="#") cnt++;
else break;
}
solve();
}
}