代码
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
const int maxn = 256;
int cnt=1,tleft[maxn],tright[maxn],value[maxn];
char s[maxn];
bool have_value[maxn];
void addnode(int v,char* s) {
int temp = 1;
if(s[0]==')') {
value[1] = v;
} else {
for(int i=0; i<strlen(s); i++) {
if(s[i]=='L') {
if(tleft[temp]==0) {
tleft[temp] = ++cnt;
}
temp = tleft[temp];
} else if(s[i]=='R') {
if(tright[temp]==0) {
tright[temp] = ++cnt;
}
temp = tright[temp];
}
}
if(have_value[temp]==false) {
value[temp] = v;
have_value[temp] = true;
} else {
value[temp] = -1;
}
}
}
void outputnode() {
queue<int> q;
bool u = true;
q.push(1);
for(int i=1; i<=cnt; i++) {
if(value[i]==-1) {
u =false;
break;
}
}
if(u) {
while(!q.empty()) {
int i = q.front();
q.pop();
cout<<value[i]<<" ";
if(tleft[i]!=0) {
q.push(tleft[i]);
}
if(tright[i]!=0) {
q.push(tright[i]);
}
}
cout<<endl;
} else {
cout<<"-1"<<endl;
}
}
void read() {
memset(s,0,sizeof(s));
memset(tleft,0,sizeof(tleft));
memset(tright,0,sizeof(tright));
memset(value,-1,sizeof(value));
memset(have_value,false,sizeof(have_value));
while(cin>>s) {
if(!strcmp(s,"()")) {
outputnode();
continue;
}
int v;
sscanf(&s[1],"%d",&v);
addnode(v,strchr(s,',')+1);
}
}
int main() {
read();
return 0;
}
测试
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200503142010693.png)