递归处理,不需要建树,每次判断当前所输出的节点是否是叶子节点,如果不是叶子节点,那么就继续处理该节点的子节点,具体细节见如下代码:
#include<iostream>
#include<vector>
#include<string>
#include<set>
#include<stack>
#include<queue>
#include<map>
#include<algorithm>
#include<cmath>
#include<iomanip>
#include<cstring>
#include<sstream>
using namespace std;
void Print(vector<string>& data,int index,int pos){
cout << data[index][pos]<<"(";
if (index + 1 < data.size()){
if (data[index + 1][pos] == '|'){
int i = pos;
while (i - 1 >= 0 && data[index + 2][i-1] == '-') i--;
while (i<data[index+2].size()&&i<data[index+3].size()&&data[index + 2][i] == '-'){
if (data[index+3][i]!=' '){
Print(data,index+3,i);
}
i++;
}
}
}
cout << ")";
}
int main(){
int T;
cin >> T;
string t;
getline(cin,t);
while (T--){
vector<string> data;
while (getline(cin, t)){
if (t == "#") break;
data.push_back(t);
}
cout << "(";
if (data.size()){
for (int i = 0; i < data[0].size(); i++){
if (data[0][i] != ' '){
Print(data, 0, i);
break;
}
}
}
cout << ")" << endl;
}
return 0;
}