注意
这里是将代码分为三部分,function.h、queue.c、main.c
同时层次遍历是需要链式队列来一起完成的
代码:
function.h代码
typedef char BiElemType;
typedef struct BiTNode
{
BiElemType c;
struct BiTNode* lchild;
struct BiTNode* rchild;
}BiTNode,*BiTree;
typedef struct tag
{
BiTree p;
struct tag* pnext;
}tag_t,*ptag_t;
typedef struct LinkNode{
ElemType data;
LinkNode *next;
};
typedef struct {
LinkNode* front;
LinkNode* rear;
}LinkQueue;
void InitQueue(LinkQueue& Q);
void EnQueue(LinkQueue& Q, ElemType e);
bool DeQueue(LinkQueue& Q, ElemType& e);
bool IsEmpty(LinkQueue Q);
queue.c代码
#include "function.h"
#include<stdio.h>
#include<stdlib.h>
void InitQueue(LinkQueue& Q)
{
Q.front = Q.rear = (LinkNode*)malloc(sizeof(LinkNode));
Q.rear->next = NULL;
}
void EnQueue(LinkQueue& Q, ElemType e)
{
LinkNode *p=(LinkNode*)malloc(sizeof(LinkNode));
p->data = e;
p->next = NULL;
Q.rear->next = p;
Q.rear = p;
}
bool DeQueue(LinkQueue& Q, ElemType& e)
{
if (Q.front == Q.rear)
{
return false;
}
LinkNode *p = Q.front->next;
e = p->data;
Q.front->next = p->next;
if (Q.rear==p)
{
Q.rear = Q.front;
}
free(p);
return true;
}
bool IsEmpty(LinkQueue Q)
{
if (Q.front == Q.rear)
{
return true;
}
else
{
return false;
}
}
main.c代码
#define _CRT_SECURE_NO_WARNINGS
#include"function.h"
#include<stdio.h>
#include<stdlib.h>
void preOrder(BiTree p)
{
if (p!=NULL)
{
putchar(p->c);
preOrder(p->lchild);
preOrder(p->rchild);
}
}
void InOrder(BiTree p)
{
if (p != NULL)
{
InOrder(p->lchild);
putchar(p->c);
InOrder(p->rchild);
}
}
void PostOrder(BiTree p)
{
if (p != NULL)
{
PostOrder(p->lchild);
putchar(p->c);
PostOrder(p->rchild);
}
}
void LevelOrder(BiTree T)
{
LinkQueue Q;
InitQueue(Q);
BiTree p = T;
EnQueue(Q, T);
while (!IsEmpty(Q))
{
DeQueue(Q, p);
putchar(p->c);
if (p->lchild != NULL)
{
EnQueue(Q, p->lchild);
}
if(p->rchild !=NULL)
{
EnQueue(Q, p->rchild);
}
}
}
int main()
{
BiTree pnew;
BiTree tree = NULL;
ptag_t phead = NULL, ptail = NULL, listpnew=NULL, pcur=NULL;
char c;
while (scanf("%c", &c) != EOF)
{
if (c == '\n')
{
break;
}
pnew = (BiTree)calloc(1, sizeof(BiTNode));
pnew->c = c;
listpnew = (ptag_t)calloc(1, sizeof(tag_t));
listpnew->p = pnew;
if (tree == NULL)
{
tree = pnew;
phead = listpnew;
ptail = listpnew;
pcur = listpnew;
continue;
}else{
ptail->pnext = listpnew;
ptail = listpnew;
}
if (NULL == pcur->p->lchild )
{
pcur->p->lchild = pnew;
}
else if (NULL == pcur->p->rchild)
{
pcur->p->rchild = pnew;
pcur = pcur->pnext;
}
}
printf("\n-----------前序遍历------------\n");
preOrder(tree);
printf("\n-----------中序遍历------------\n");
InOrder(tree);
printf("\n-----------后序遍历------------\n");
PostOrder(tree);
printf("\n-----------层次遍历------------\n");
LevelOrder(tree);
return 0;
}