二叉树层次遍历算法实现
问题描述
对任意输入的表示某二叉树的字符序列,完成二叉树的层次遍历算法,并输出其遍历结果。
注:所需Queue ADT的实现见附录。
输入描述
从键盘上输入一串字符串,该字符串为二叉树的先序遍历结果,其中如果遍历到空树时用字符”#”代替。
输出描述
从显示器上输出二叉树的按层次遍历结果。
输入与输出示例
输入:
+A##/*B##C##D##
输出:
+A/*DBC
输入:
ABD##GJ###CFH##I###
输出:
ABCDGFJHI
附录(仅供参考):
#include<stdio.h>
#include<malloc.h>
#define TRUE 1
#define FALSE 0
#define MAX_QUEUE_SIZE 100
//注:需要定义ElementType类型,如果是二叉树,
// 则应定义为指向二叉树中结点的指针类型
//格式如:
// typedef Tree ElementType;
// 队列存储结构采用循环队列
struct QueueRecord;
typedef struct QueueRecord *Queue;
int IsEmpty(Queue Q);
int IsFull(Queue Q);
Queue CreateQueue(int MaxElements);
void DisposeQueue(Queue Q);
void MakeEmpty(Queue Q);
int Enqueue(ElementType X, Queue Q);
ElementType Front(Queue Q);
int Dequeue(Queue Q, ElementType &X);
#define MinQueueSize ( 5 )
struct QueueRecord
{
int Capacity;
int Front;
int Rear;
ElementType *Array;
};
int IsEmpty(Queue Q)
{
return ((Q->Rear + 1)% Q->Capacity == Q->Front); }
int IsFull(Queue Q)
{
return ((Q->Rear + 2) % Q->Capacity == Q->Front); }
Queue CreateQueue(int MaxElements)
{
Queue Q;
if (MaxElements < MinQueueSize)
return NULL;
Q = (Queue)malloc(sizeof(struct QueueRecord));
if (Q == NULL) return NULL;
Q->Array = (ElementType *)malloc(
sizeof(ElementType) * MaxElements);
if (Q->Array == NULL) return NULL;
Q->Capacity = MaxElements;
MakeEmpty(Q);
return Q;
}
void DisposeQueue(Queue Q)
{
if (Q != NULL)
{
free(Q->Array);
free(Q);
}
}
void MakeEmpty(Queue Q)
{
Q->Front = 1;
Q->Rear = 0;
}
static int Succ(int Value, Queue Q)
{
if (++Value == Q->Capacity)
Value = 0;
return Value;
}
int Enqueue(ElementType X, Queue Q)
{
if (IsFull(Q)) return FALSE;
else
{
Q->Rear = Succ(Q->Rear, Q);
Q->Array[Q->Rear] = X;
}
}
ElementType Front(Queue Q)
{
if (IsEmpty(Q)) return FALSE;
return Q->Array[Q->Front];
}
int Dequeue(Queue Q, ElementType &X)
{
if (IsEmpty(Q))
{
return FALSE;
}
else
{
X = Q->Array[Q->Front];
Q->Front = Succ(Q->Front, Q);
}
return TRUE;
}。