重新复习了下树的遍历,我是直接在主函数先写了一次遍历的代码,然后改成无限次遍历但最后不是以文件结束,
但题目要求是以文件结束,因为不是做工程,也懒得改成函数了,在读写字符串的时候判断一下EOF,直接return 0。
输出也是坑,最后一个元素输出还不能有空格。。。
整理下出错的地方:
1、新建结点时应该新建指针,node*类型的。
2、必须写构造函数并且赋值空指针NULL,要不就初始化的时候直接NULL,不然会出现段错误。
代码有点乱。。。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>
using namespace std;
struct node{
int v;
int tag;
node *ll;
node *rr;
node():tag(0),ll(NULL),rr(NULL){}//构造函数 必须要有
};
int ok;
/*void dfs(node* t)
{
if(t==NULL)return;
cout<<t->v<<" ";
dfs(t->ll);
dfs(t->rr);
}*/
void bfs(node* t)
{
queue<node*> q;
vector<int> ans;
q.push(t);
while(!q.empty())
{
node* m=q.front();
q.pop();
if(m->tag==0){
ok=0;
break;
}
ans.push_back(m->v);
if(m->ll!=NULL)q.push(m->ll);
if(m->rr!=NULL)q.push(m->rr);
}
if(ok){
for(int i=0;i<ans.size();i++)
printf("%d%c", ans[i], i == ans.size() - 1 ? '\n' : ' '); //输出坑
}
else
printf("not complete\n");
}
int main()
{
while(1)
{
node* root;
root=new node();
ok=1;
while(1)
{
string str;
if(!(cin>>str))return 0;//当end of file时退出程序
if(str=="()")break;
int value;
sscanf(&str[1],"%d",&value);
string s=str.substr(str.find(',')+1);//子串
int len=s.length();
node* u=root;
for(int i=0;i<len;i++)//将结点插入树。
{
if(s[i]=='L')
{
if(u->ll == NULL) u->ll=new node();
u = u->ll;
}
else if(s[i]=='R')
{
if(u->rr==NULL)u->rr=new node();
u=u->rr;
}
}
if(u->tag)ok=0;
u->v=value;
u->tag=1;
}
bfs(root);
}
return 0;
}