层次遍历
#include <iostream>
#include <string>
#include <sstream>
using namespace std ;
const int MAXN = 256 ;
const int root = 1 ;
int cnt , vis[MAXN] , val[MAXN] , Left[MAXN] , Right[MAXN] ;
int NewNode() {
int u = ++cnt ;
Left[u] = Right[u] = 0 ;
return u ;
}
void NewTree() {
Left[root] = Right[root] = 0 ;
cnt = root ;
}
int failed ;
void AddNode(int value , string word) {
int u = root ;
for (size_t i = 0 ; i < word.size() ; i ++) {
if (word.at(i) == 'L') {
if (!Left[u]) {
Left[u] = NewNode() ;
}
u = Left[u] ;
}
else if (word.at(i) == 'R') {
if (!Right[u]) {
Right[u] = NewNode() ;
}
u = Right[u] ;
}
}
if (vis[u]) {
failed = 1 ;
}
val[u] = value ;
vis[u] = 1 ;
}
int Input_Read() {
cnt = 0 ;
memset(vis,0,sizeof(vis)) ;
failed = 0 ;
NewTree() ;
string word ;
while (true) {
cin >> word ;
if (cin.eof()) {
return 0 ;
}
if (word == "()") {
break ;
}
stringstream sin(word) ;
int tmp ;
sin.ignore(1) ;
sin >> tmp ;
AddNode(tmp,strchr(word.c_str(),',')+1) ;
}
return 1 ;
}
int n = 0 , ans[MAXN] ;
int bfs() {
int front = 0 , rear = 1 ;
int q[MAXN] ;
q[0] = root ;
memset(ans,0,sizeof(ans)) ;
while (front < rear) {
int u = q[front++] ;
if (!vis[u]) {
return 0 ;
}
ans[n++] = val[u] ;
if (Left[u]) {
q[rear++] = Left[u] ;
}
if (Right[u]) {
q[rear++] = Right[u] ;
}
}
return 1 ;
}
int main() {
while (Input_Read()) {
if (!bfs()) {
failed = 1 ;
}
if (failed) {
cout << -1 << endl ;
}
else {
for (int i = 0 ; i < n ; ++ i) {
cout << ans[i] << " " ;
}
cout << endl ;
}
}
return 0 ;
}
#include<iostream>
using namespace std;
const int MAXN=256;
char s[MAXN+10];
int n,ans[MAXN];
int failed;
typedef struct Tnode
{
int have_value;
int v;
struct Tnode* left,*right;
}Node;
Node* root;
Node* newnode()
{
Node* u=(Node*) malloc(sizeof(Node));
if(u!=NULL)
{
u->have_value=0;
u->left=u->right=NULL;
}
return u;
}
void addnode(int v,char* s)
{
int n=strlen(s);
Node* u=root;
for(int i=0;i<n;++i)
{
if(s[i]=='L')
{
if(u->left==NULL)u->left=newnode();
u=u->left;
}
else if(s[i]=='R')
{
if(u->right==NULL)u->right=newnode();
u=u->right;
}
}
if(u->have_value)
failed=1;
u->v=v;
u->have_value=1;
}
void remove_tree(Node* u)
{
if(u==NULL)
return;
remove_tree(u->left);
remove_tree(u->right);
free(u);
}
int read_input()
{
failed=0;
remove_tree(root);
root=newnode();
for(;;)
{
if(scanf("%s",s)!=1)
return 0;
if(!strcmp(s,"()"))
break;
int v;
sscanf(&s[1],"%d",&v);
addnode(v,strchr(s,',')+1);
}
return 1;
}
int bfs()
{
int front=0;
int rear=1;
Node* q[MAXN];
q[0]=root;
while(front<rear)
{
Node* u=q[front++];
if(!u->have_value)
return 0;
ans[n++]=u->v;
if(u->left!=NULL)
q[rear++]=u->left;
if(u->right!=NULL)
q[rear++]=u->right;
}
return 1;
}
int main()
{
read_input();
bfs();
if(failed==1)
cout<<"-1"<<endl;
else
for(int i=0;i<n;++i)
cout<<ans[i]<<" ";
system("pause");
return 0;
}