【例题 6-7 UVA - 122 】Trees on the level
【链接】 我是链接,点我呀:)
【题意】
【题解】
二叉树的话,直接用数组存就好了。 写个bfs记录一下答案。【代码】
#include <bits/stdc++.h>
using namespace std;
const int N = 300;
string s;
int g[N+10][3],cnt;
vector <int> ans;
bool bfs(){
queue <int> dl;
dl.push(0);
while (!dl.empty()){
int x = dl.front();
dl.pop();
if (!g[x][2]) return false;
ans.push_back(g[x][2]);
for (int i = 0;i < 2;i++)
if (g[x][i])
dl.push(g[x][i]);
}
return true;
}
int main(){
// freopen("rush.txt","r",stdin);
while (cin >> s){
ans.clear();
memset(g,0,sizeof g);
cnt = 0;
bool ok = true;
while (!(s[0]=='(' && s[1]==')')){
int len = s.size();
bool root = false;
for (int i = 0;i < len;i++)
if (s[i]=='(' || s[i]==')' || s[i]==',') {
if (s[i]==',' && i+1<len && s[i+1]==')') root = true;
s[i]=' ';
}
stringstream ss(s);
int x;
ss >> x >> s;
if (root) s = "";
int now = 0;
for (int i = 0;i < (int) s.size();i++){
if (s[i]=='L'){
if (!g[now][0]) g[now][0] = ++cnt;
now = g[now][0];
}else{
if (!g[now][1]) g[now][1] = ++cnt;
now = g[now][1];
}
}
if (g[now][2]==0)
g[now][2] = x;
else{
ok = false;
}
cin >> s;
}
if (!ok || !bfs()){
puts("not complete");
}else{
for (int i = 0;i < (int) ans.size();i++){
printf("%d",ans[i]);
if (i==(int)ans.size()-1){
puts("");
}else putchar(' ');
}
}
}
return 0;
}