#include<stdio.h>
#include<stdlib.h>
#define MaxSize 50
typedef char ElemType;
typedef struct BTNode
{
ElemType data;
struct BTNode *left;
struct BTNode *right;
}BTNode,*BiTree;
typedef struct Queue
{
BTNode *data[MaxSize]; //注意这里的data要设置为树节点类型
int rear,front;
}Queue;
void InitQueue(Queue &Q) //初始化栈
{
Q.rear = Q.front = 0;
}
bool IsQueueEmpty(Queue Q) //判断栈是否为空
{
if(Q.front == Q.rear)
return true;
else
return false;
}
void EnQueue(Queue &Q,BTNode *B) //进队列
{
Q.data[Q.rear] = B;
Q.rear = (Q.rear+1)%MaxSize;
}
void DeQueue(Queue &Q,BTNode *&B) //出队列
{
B = Q.data[Q.front];
Q.front = (Q.front+1)%MaxSize;
}
void createBiTree(BTNode *&BT) //创建二叉树
{
ElemType ch;
scanf("%c",&ch);
if(ch==' ')
BT=NULL;
else
{
BT = (BTNode*)malloc(sizeof(BTNode));
BT->data = ch;
createBiTree(BT->left);
createBiTree(BT->right);
}
}
void DLR(BiTree B) //先序遍历二叉树
{
if(B)
{
printf("%c ",B->data);
DLR(B->left);
DLR(B->right);
}
}
void levelOrder(BiTree B) //层次遍历二叉树
{
Queue Q;
BTNode *x;
InitQueue(Q);
if(B)
EnQueue(Q,B);
else
printf("空树!\n");
while(!IsQueueEmpty(Q))
{
DeQueue(Q,x);
if(x)
{
printf("%c ",x->data);
EnQueue(Q,x->left);
EnQueue(Q,x ->right);
}
}
printf("\n");
}
void main()
{
BiTree B;
createBiTree(B);
printf("先序遍历:");
DLR(B);
printf("\n");
printf("层次遍历:");
levelOrder(B);
}
按先序遍历来依次输入二叉树结点,若无孩子结点则输入空格。
如输入:
ABD E CF
输出:
先序遍历:A B D E C F
层次遍历:A B C D E F