/*二叉树前序、中序、层次层次遍历*/
#include<stdio.h>
#include<malloc.h>
typedef char ElemType;
typedef struct BiTNode
{
ElemType val;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
typedef struct LinkNode
{
BiTNode *data;
struct LinkNode *next;
}LinkNode;
typedef struct
{
LinkNode *front,*rear;
}LinkQueue;
void InitQueue(LinkQueue &Q) //初始化队列
{
Q.front=Q.rear=(LinkNode *)malloc(sizeof(LinkNode));
Q.front->next=NULL;
}
bool EmptyQueue(LinkQueue Q) //判断队列是否为空
{
if(Q.rear==Q.front)
return true;
else
return false;
}
void EnQueue(LinkQueue &Q,BiTree p) //树节点入队
{
LinkNode *q;
q=(LinkNode *)malloc(sizeof(LinkNode));
q->data=p;
q->next=NULL;
Q.rear->next=q;
Q.rear=q;
}
bool DeQueue(LinkQueue &Q,BiTree &p) //树节点出队
{
if(EmptyQueue(Q))
return false;
LinkNode *q=Q.front->next;
p=q->data;
Q.front->next=q->next;
if(Q.rear==q)
Q.rear=Q.front;
free(q);
return true;
}
BiTree IniTree() //初始化树
{
BiTree t;
char ch;
ch=getchar();
if(ch == '#')
t=NULL;
else
{
t=(BiTree)malloc(sizeof(BiTNode));
t->val=ch;
t->lchild=IniTree();
t->rchild=IniTree();
}
return t;
}
void visit(BiTree T) //访问树节点
{
printf("%c",T->val);
}
bool proOrder(BiTree T) //先序遍历
{
if(T==NULL)
return false;
else
{
visit(T);
proOrder(T->lchild);
proOrder(T->rchild);
}
return true;
}
bool inOrder(BiTree T) //中序遍历
{
if(T==NULL)
return false;
else
{
inOrder(T->lchild);
visit(T);
inOrder(T->rchild);
}
}
bool postOrder(BiTree T) //后序遍历
{
if(T==NULL)
return false;
else
{
postOrder(T->lchild);
postOrder(T->rchild);
visit(T);
}
}
void LevelOrder(BiTree T) //层次遍历
{
LinkQueue Q;
InitQueue(Q);
BiTree p;
if (T!=NULL)
EnQueue(Q,T); //根节点入队
while(!EmptyQueue(Q))
{
DeQueue(Q,p); //队头节点出队
visit(p);
if(p->lchild!=NULL)
EnQueue(Q,p->lchild); //左子树不空,左子树根节点入队
if(p->rchild!=NULL)
EnQueue(Q,p->rchild); //右子树不空,右子树根节点入队
}
}
void main()
{
BiTree T;
printf("按先序序列输入结点序列,'#'代表空: ");
T=IniTree();
printf("\n先序遍历:");
proOrder(T);
printf("\n中序遍历:");
inOrder(T);
printf("\n后序遍历:");
postOrder(T);
printf("\n层次遍历:");
LevelOrder(T);
printf("\n");
}
/*感谢一位陌生大佬的帮助*/