时间限制: 15 Sec 内存限制: 128 MB
提交: 606 解决: 517
题目描述
从键盘接收扩展先序序列,以二叉链表作为存储结构,建立二叉树。输出这棵二叉树的层次遍历序列。
样例输入 Copy
ABC##DE#G##F###
样例输出 Copy
ABCDEFG
#include<stdio.h>
#include<stdlib.h>
#define MAX_SIZE 100
//节点类型定义
typedef struct Node{
char data;
struct Node* Lchild;
struct Node* Rchild;
}BiTNode, *BiTree;
//定义队列
typedef struct{
BiTNode node[MAX_SIZE];
int front, rear;
}SeqQueue;
//初始化队列
int InitQueue(SeqQueue *Q)
{
//Q = (SeqQueue *)malloc(sizeof(SeqQueue));
Q->front = Q->rear = -1;
}
//判空
int IsEmpty(SeqQueue *Q)
{
if(Q->front == Q->rear)
return 1;
return 0;
}
//入队
int EnterQueue(SeqQueue *Q, BiTNode* p)
{
if(Q->rear == MAX_SIZE-1)
return 0;
Q->rear++;
Q->node[Q->rear] = *p;
return 1;
}
//出队
int DeleteQueue(SeqQueue *Q, BiTNode* p)
{
if(IsEmpty(Q))
{
return 0;
}
else
{
Q->front++;
*p = Q->node[Q->front];
return 1;
}
}
//访问节点
/*void Visit(BiTNode p)
{
printf("%c ", p.data);
}*/
//层次遍历二叉树
void LevelOrder(BiTree root)
{
SeqQueue Q;
BiTree p, q;
InitQueue(&Q);
EnterQueue(&Q, root);
q = root;
while(!IsEmpty(&Q))
{
p = q;
DeleteQueue(&Q, p);
printf("%c", p->data);
if(p->Lchild != NULL)
{
EnterQueue(&Q, p->Lchild);
}
if(p->Rchild != NULL)
{
EnterQueue(&Q, p->Rchild);
}
}
}
//用扩展先序遍历建立二叉链表
void CreateBiTree(BiTree *root)
{
char ch;
ch = getchar();
if(ch == '#')
*root = NULL;
else
{
(*root) = (BiTree)malloc(sizeof(BiTNode));
(*root)->data = ch;
CreateBiTree(&((*root)->Lchild));
CreateBiTree(&((*root)->Rchild));
}
}
int main()
{
BiTree root = NULL;
CreateBiTree(&root);
LevelOrder(root);
}