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

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

2019-08-04 00:28 260 查看

数据结构实验之二叉树五:层序遍历
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description

已知一个按先序输入的字符序列,如abd,eg,cf,(其中,表示空结点)。请建立二叉树并求二叉树的层次遍历序列。
Input
输入数据有多行,第一行是一个整数t (t<1000),代表有t行测试数据。每行是一个长度小于50个字符的字符串。
Output
输出二叉树的层次遍历序列。
Sample Input

2
abd,eg,cf,
xnl,i,u,

Sample Output

abcdefg
xnuli

**

层序遍历 有好几种方法,以后接触到我会更新。现在说一下这个代码里的思路,他是通过运用队的思路来实现的 例如图中这颗树,首先读取a,输出a,然后把它的左右子树输入,cd,此时输出c,把c的左右子树输入,此时堆栈内容为 d e g,然后输出d,同时将d的左右子树输出,这时队中为e g b n,就这样,输出了acdegbn。

**

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<queue>

using namespace std;

struct Tree
{
Tree *l, *r;
char data;
};
int i;
char s[55];
Tree *creat()
{
char ch = s[i++];
Tree *tree;
if(ch == ',')
tree = NULL;
else
{
tree = (Tree *)malloc(sizeof(Tree));
tree->data = ch;
tree->l = creat();
tree->r = creat();
}
return tree;
}
void cengxu(Tree *tree)
{
queue<Tree *>q;
Tree *p = tree;
if(p) q.push(p);
while(!q.empty())
{
p = q.front();
q.pop();
printf("%c", p->data);
if(p->l)
q.push(p->l);
if(p->r)
q.push(p->r);
}
}

/* 不用队列:
void cengxu2(Tree *tree)
{
Tree *temp[55];//关键中间变量存放每一层的数据
int in = 0,out = 0;
temp[in++] = tree;//每次把这一层存入,然后输出的时候就把他的左右节点存入
while(in > out)   //例如一颗完全二叉树abcdefg  输出a的时候把bc放入,输出b的时候把b
{                 //的孩子放入也就是de,再输出c并且放入孩子fg,依次这样,达到层序的要求
if(temp[out])
{
printf("%c", temp[out]->data);
temp[in++] = temp[out]->l;
temp[in++] = temp[out]->r;
}
out++;
}
}*/
int main()
{
int n;
scanf("%d", &n);
while(n--)
{
i = 0;
scanf("%s", s);
Tree *tree;
tree = creat();
cengxu(tree);
printf("\n");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: