1.树的添加+bfs例题:uva122
#include <iostream>
#include <stdio.h>
#include <vector>
#include <queue>
#include <string.h>
using namespace std;
struct Node
{
int data;
bool vis;
Node* ls;
Node* rs;
Node()
{
vis=false;
ls=NULL;
rs=NULL;
}
};
char s[300];
Node *root;
bool flag;
void addnode()
{
Node * p=root;
int data_;
sscanf(&s[1],"%d",&data_);//必须从第一个是数字的算起
int i;
for(i=2; s[i]!='L' && s[i]!='R' && s[i]!=')'; i++);
if(s[i]==')')
{
root->data=data_;
root->vis=true;
return ;
}
for(; s[i]!=')'; i++)
{
if(s[i]=='L')
{
if(p->ls==NULL)
p->ls=new Node();
p=p->ls;
}
else
{
if(p->rs==NULL)
p->rs=new Node();
p=p->rs;
}
}
if(p->vis) flag=false;
p->data=data_;
p->vis=true;
}
vector<int> ans;
queue<Node*> q;
int read()
{
while(!q.empty())
q.pop();
ans.clear();
flag=true;
root = new Node();
if(scanf("%s",s)==0 || strcmp(s,"()")==0) return 0;
addnode();
while(scanf("%s",s) && strcmp(s,"()")!=0)
addnode();
return 1;
}
bool bfs()
{
Node*tmp;
q.push(root);
while(!q.empty())//如果程序在中间就return了,q就不为空!
{
tmp=q.front();
if(tmp->ls!=NULL)
{
if(tmp->vis)
q.push(tmp->ls);
else
return false;
}
if(tmp->rs!=NULL)
{
if(tmp->vis)
q.push(tmp->rs);
else
return false;
}
ans.push_back(tmp->data);
q.pop();
}
return true;
}
int main()
{
while(read())
{
if(!bfs() || !flag)
printf("not complete\n");
else
{
for(int i=0; i<ans.size(); i++)
printf("%d%c",ans[i],i==ans.size()-1?'\n':' ');
}
}
return 0;
}
/*
(129,) (399,R) (556,L) (77,RL) ()
(382,RLLLRL) (641,RLL) (571,R) (460,RLLLRLL) (335,RL) (643,RLLLRR) (797,RLLLR) (309,RLLLL) ()
*/