输出利用先序遍历创建的二叉树的层次遍历序列
利用先序递归遍历算法创建二叉树并输出该二叉树的层次遍历序列。先序递归遍历建立二叉树的方法为:按照先序递归遍历的思想将对二叉树结点的抽象访问具体化为根据接收的数据决定是否产生该结点从而实现创建该二叉树的二叉链表存储结构。约定二叉树结点数据为单个大写英文字符。当接收的数据是字符"#“时表示该结点不需要创建,否则创建该结点。最后再输出创建完成的二叉树的层次遍历序列。需要注意输入数据序列中的”#“字符和非”#"字符的序列及个数关系,这会最终决定创建的二叉树的形态。
输入
输入为接受键盘输入的由大写英文字符和"#"字符构成的一个字符串(用于创建对应的二叉树)。
输出
每个用例用一行出该用例对应的二叉树的层次遍历序列。
样例输入
A##
ABC####
AB##C##
ABCD###EF##G##H##
A##B##
样例输出
A
ABC
ABC
ABHCEDFG
A
利用队列进行层次遍历
算法实现:
1.初始化队列,并将根结点入队列
2.当非空队列时,循环执行3~6,否则执行7
3.出队列取得一个结点,访问该结点
4.如果改结点的右结点不为空,则入队列
5.如果改结点的左结点不为空,则入队列
6.输出当前结点的数据
7.退出程序
代码如下:
#include<iostream>
#include<cstdlib>
using namespace std;
const int maxsize = 100;
typedef struct List
{
char data;
struct List *l, *r;
}list;
typedef struct Queue
{
int front, rear;
struct List *ecc[maxsize];
}queue;
queue *q;
void enqueue(queue *&q,list *e)//将结点入队列
{
q->rear = (q->rear + 1) % maxsize;
q->ecc[q->rear] = e;
}
void pushqueue(queue *&q, list *&e)//出队列
{
q->front = (q->front + 1) % maxsize;
e = q->ecc[q->front];
}
void creat(list *&head) //创建树
{
char a;
cin >> a;
if (a != '#')
{
head = new list;
head->data = a;
creat(head->l);
creat(head->r);
}
else
head = NULL;
}
void getch(list *&head)
{
list *c;
if (head != NULL)
{
enqueue(q,head);
}
while (q->front != q->rear)
{
pushqueue(q, c);
if (c->l != NULL)
enqueue(q, c->l);
if (c->r != NULL)
enqueue(q, c->r);
cout << c->data;
}
}
int main()
{
q = new queue;
q->front = q->rear = 0; //初始化队列
list *head;
creat(head);
getch(head);
}