王道oj/problem21
网址:oj.lgwenda.problem/21
思路:先序遍历,中序遍历,后序遍历用递归实现;层序遍历用一个链队实现,出队一个元素,顺序入队他的左孩子和右孩子
代码:
#define _CRT_SECURE_NO_WARNINGS
#include
#include
typedef char BiElemType;
typedef struct BiTNode
{
BiElemType c=0;
struct BiTNode* lchild=NULL;
struct BiTNode* rchild=NULL;
}BiTNode,*BiTree;
typedef BiTree ElemType;
typedef struct tag {
BiTree p;//树的某一个结点的地址值
struct tag* pnext=NULL;
}tag_t, * ptag_t;
typedef struct LinkNode {
ElemType 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 IsEmpty(LinkQueue Q)
{
if (Q.front == Q.rear)
return true;
else
return false;
}
void EnQueue(LinkQueue& Q, ElemType x)
{
LinkNode* s = (LinkNode*)malloc(sizeof(LinkNode));
s->data = x;
Q.rear->next = s;
Q.rear = s;
Q.rear->next = NULL;
}
bool DeQueue(LinkQueue& Q, ElemType& x)
{
if (Q.rear == Q.front)return false;
LinkNode* p = Q.front->next;
x = p->data;
Q.front->next = p->next;
if (p == Q.rear)
Q.rear = Q.front;
free(p);
return true;
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 AfterOrder(BiTree p)
{
if (p != NULL)
{
AfterOrder(p->lchild);
AfterOrder(p->rchild);
putchar(p->c);
}
}
void LevelOrder(BiTree T)
{
LinkQueue Q;
InitQueue(Q);
BiTree p;
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=NULL;
int i, j, pos;
char c;
BiTree tree = NULL;
ptag_t phead = NULL, ptail = NULL, listpnew=NULL,pcur=NULL;//phead就是队列头,ptail就是队列尾
while (scanf("%c", &c) != EOF)
{
if (c == '\n')
{
break;
}
pnew = (BiTree)calloc(1,sizeof(BiTNode));//calloc申请空间并对空间进行初始化,赋值为0
pnew->c = c;//数据放进去
listpnew = (ptag_t)calloc(1,sizeof(tag_t));//给队列节点申请空间
listpnew->p = pnew;
if (NULL == tree)
{
tree = pnew;
phead = listpnew;
ptail = listpnew;
pcur = listpnew;
continue;
}else {
ptail->pnext = listpnew;//新结点放入链表,通过尾插法
ptail = listpnew;//ptail指向队列尾部
}//pcur始终指向要插入的结点的位置
if (NULL == pcur->p->lchild)//如何把新结点放入树
{
pcur->p->lchild = pnew;//把新结点放到要插入结点的左边
}else if(pcur->p->rchild==NULL){
pcur->p->rchild = pnew;
pcur = pcur->pnext;//左右都放了结点,指向下一个
}
}
//printf("----------以下是前序遍历-----------\n");
//preOrder(tree);
InOrder(tree);
printf("\n");
AfterOrder(tree);
printf("\n");
LevelOrder(tree);
}