尽量用的STL,运行效率有很大缺失,不过更容易理解,读者自行写C语言格式吧。
#include<iostream>
#include<cstdio>
#include<malloc.h>
#include<string>
#include<sstream>
#include<queue>
using namespace std;
struct Node{
bool have_value;
int v;
Node *left, *right;
Node() :have_value(0) ,left(NULL),right(NULL){}
};
Node *newnode(){
Node *u=(Node *)malloc(sizeof(Node));
u->have_value=0;
u->left=NULL;
u->right=NULL;
return u;
}
Node *head;
int failed;
void addnode(int v,string s){
Node *u=head;
for(string :: iterator t=s.begin();t !=s.end(); t++){
if(*t=='L'){
if(u->left == NULL) u->left=newnode();
u= u->left;
}
else if(*t=='R'){
if(u->right == NULL) u->right=newnode();
u= u->right;
}
}
if(u->have_value==1) (failed = 1);//cout<<"=";
u->have_value = 1;
u->v = v;
}
vector<int> ans;
int bfs(vector<int> &ans){
queue<Node*> q;
ans.clear();
q.push(head);
while(!q.empty()){
Node* u =q.front(); q.pop();
if(!u->have_value) return 1;//错了
ans.push_back(u->v);
if(u->left!=NULL) q.push(u->left);
if(u->right!=NULL) q.push(u->right);
}
return 0;
}
void remove_tree(Node* u) {
if(u == NULL) return;
remove_tree(u->left);
remove_tree(u->right);
free(u);
}
int input(){
remove_tree(head);
head=newnode();
failed=0;
string s,key;
while(cin>>s){
if(s=="()") return 1;
int value;
for(unsigned i =0; i<s.length(); i++)
if(s[i]=='('||s[i]==',') s[i]=32;
stringstream ss(s);
ss>>value>>key;
//cout<<value<<" "<<key<<endl;//
addnode(value,key);
//cout<<"="<<endl;
}
return 0;
}
int main(){
while(input()){
vector<int> q;
bfs(q)&&(failed=1);
if(failed) cout<<"not complete"<<endl;
else{
for(unsigned i =0;i<q.size(); i++){
if(i) cout<<" ";
cout<<q[i];
}
cout<<endl;
}
}
return 0;
}