您的位置:首页 > 理论基础 > 数据结构算法

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

2017-01-03 13:15 495 查看

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

Time Limit: 1000MS
Memory Limit: 65536KB
[align=center][/align]

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


Hint

 

Author

 xam    

思路:

1,用数组层次存储树

2,用队列层次遍历二叉树

代码1

具体思路:将树的每个节点按层次存入数组中,先存入该节点以及两子树,后输出对应内容

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
char s[100000];
int i;
typedef struct Tree{
char d;
struct Tree *l,*r;
}Tree;
Tree *T;
void Creat(Tree *&T){
char x;
x=s[i++];
if(x==','){
T=NULL;
return;
}
else{
T=new Tree;
T->d=x;
Creat(T->l);
Creat(T->r);
}
}
void Traverse(Tree *root)
{
int out=0,in=0;
Tree *q[100]; ///创建数组存放每个节点
q[in++]=root; ///存入根节点,由此扩展
while(in>out) ///判断所有节点是否遍历完毕
{
if(q[out]) ///判断数组该位置的节点是否可扩展
{
printf("%c",q[out]->d);
q[in++]=q[out]->l;
q[in++]=q[out]->r;
}
out++; ///有空节点依旧向后层次遍历
}
}
int main(){
int n;
//freopen("F://1.txt","r",stdin);
while(~scanf("%d",&n)){
for(int j=0;j<n;j++){
scanf("%s",s);
T=NULL; ///及时清空原有树
i=0; ///注意及时置0,否则多组数据输入爆掉
Creat(T);
Traverse(T);
printf("\n");
}

}
return 0;
}


代码2

具体思路:经典的队列实现层次遍历,进队顺序即为层次遍历顺序,边进边出,及时更新队首元素

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
char s[100000];
int i;
typedef struct Tree{
char d;
struct Tree *l,*r;
}Tree;
Tree *T;
queue <Tree> q;
void Creat(Tree *&T){
char x;
x=s[i++];
if(x==','){
T=NULL;
return;
}
else{
T=new Tree;
T->d=x;
Creat(T->l);
Creat(T->r);
}
}
void Traverse(Tree *T)
{
queue <Tree*> q;
Tree *p;
p=NULL;
if(T){
q.push(T); ///跟节点入队
}
while(!q.empty()){
p=q.front(); ///记录根节点,对被记录点扩展
q.pop(); ///更新队列
cout<<p->d; ///出队同时输出对应内容
if(p->l)
{
q.push(p->l); ///被记录点左子树不为空,入队
}
if(p->r)
{
q.push(p->r); ///被记录点右子树不为空,入队
}
}
}
int main(){
int n;
//freopen("F://1.txt","r",stdin);
while(~scanf("%d",&n)){
for(int j=0;j<n;j++){
scanf("%s",s);
T=NULL; ///及时清空原有树
i=0; ///注意及时置0,否则多组数据输入爆掉
Creat(T);
Traverse(T);
printf("\n");
}
}
return 0;
}


革命尚未成功!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: