数据结构实验之二叉树五:层序遍历

本文介绍了一种通过队列实现二叉树层次遍历的方法,并提供了完整的C++代码示例。输入先序遍历的字符序列,程序能够构建二叉树并输出其层次遍历结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem Description

已知一个按先序输入的字符序列,如abd,,eg,,,cf,,,(其中,表示空结点)。请建立二叉树并求二叉树的层次遍历序列。

Input
 输入数据有多行,第一行是一个整数t (t<1000),代表有t行测试数据。每行是一个长度小于50个字符的字符串。
Output
 输出二叉树的层次遍历序列。
Example Input
2
abd,,eg,,,cf,,,
xnl,,i,,u,,
Example Output
abcdefg
xnuli

    层序遍历借助了队列这种结构,先将根节点加入队列,在循环中每次都将队首的节点移出,同时将队首节点的左右子节点加入队列中,直到队列为空。

#include <iostream>
#include <queue>
#include <string>
using namespace std;
char s[55];
int pos = -1;
struct node
{
	char data;
	node *l,*r;
};

struct node *creat()
{
	node *t;
	if(s[++pos] == ',')
		return NULL;
	t = new node;
	t->data = s[pos];
	t->l = creat();
	t->r = creat();
	return t;
}
void levelshow(struct node *t)
{
	queue<node *>Q;
	node *temp;
	Q.push(t);
	while(!Q.empty())
	{
		temp = Q.front();
		Q.pop();
		if(temp)
		{
			cout<<temp->data;
			Q.push(temp->l);
			Q.push(temp->r);
		}
	}
}
int main(int argc, char const *argv[])
{
	node *root;
	int t;
	cin>>t;
	while(t--)
	{
		pos = -1;
		cin>>s;
		root = creat();
		levelshow(root);
		cout<<endl;
	}
	return 0;
}


 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值