UVa122 树的层序遍历

重新复习了下树的遍历,我是直接在主函数先写了一次遍历的代码,然后改成无限次遍历但最后不是以文件结束,

但题目要求是以文件结束,因为不是做工程,也懒得改成函数了,在读写字符串的时候判断一下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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值