// 层次遍历
//
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
using namespace std;
#include <string>
#define MaxSize 100
typedef struct BiTNode {
char data;
struct BiTNode *lchild,*rchild;
}BiTNode ,*BiTree;//二叉链表存储二叉树
typedef struct QNode{
BiTNode *data;
struct QNode *next;
}QNode,*Queue;
typedef struct {
Queue front;
Queue rear;
}Linkqueue;
//队列的基本操作
int Initqueue(Linkqueue &Q) //初始化队列
{
Q.front=Q.rear=(Queue)malloc(sizeof(QNode));
if(!Q.front)
exit(1);
Q.front->next=NULL;
return 1;
}
int Enqueue(Linkqueue &Q, BiTNode *e)//入队列
{
Queue p;
p=(Queue)malloc(sizeof(QNode));
if(!p)
exit(1);
p->data=e;
p->next=NULL;
Q.rear->next=p;
Q.rear=p;
return 1;
}
int Dequeue(Linkqueue &Q, BiTNode *e)
{
if(Q.front==Q.rear)return 0;
Queue p;
p=Q.front->next;
e=p->data;
Q.front->next=p->next;
if(Q.rear==p)
Q.rear=Q.front;
free(p);
return 1;
}
int Emptyqueue(Linkqueue Q)
{
if(Q.rear==Q.front)
return 0;
}
BiTNode* CreateBiTree(BiTree T)//按层次建立二叉树 yecy:build bitTree commonly used recursive function or non-recursive function
{//yecy remove param T (not use in the function)
char ch;//replace ch ==> itemData
BiTree Q[MaxSize]; //以数组存储结点
int front,rear;//yecy
BiTNode* root,*s;// replace s ==> newNode
root=NULL;
front=1;rear=0;// yecy: why ? replace front = 1 ==> front =0
printf("请按照层次输入树的结点,'.'表示该结点为空
");
ch=getchar();
//getchar(); //yecy: remove it
while(ch!='?')//输入为?时表示停止输入 yecy: replace it ==> '?' != ch
{
s=NULL;
if(ch!='.')
{
s=(BiTree)malloc(sizeof(BiTNode));
s->data=ch;
s->lchild=NULL;
s->rchild=NULL;
}
//rear++;//yecy: array index begin 0, remove it
Q[rear]=s;
if(rear==1)
root=s;//只有一个结点即为根结点
else
{
if(s&&Q[front])//yecy:replace it ==> s && Q[rear]
if(rear%2==0)//yecy: replace it ==> 1 == rear%2
Q[front]->lchild=s;//yecy replace it ==> Q[rear % 2]->lchild=s
else
Q[front]->rchild=s;//yecy replace it ==> Q[rear % 2]->rchild=s
if(rear%2==1)//yecy:remove it
front++;//yecy: replace it ==> ++rear
}
ch=getchar();
//getchar();//yecy remove it
}
return root;
}
void Visit(char S) //遍历操作——访问结点的信息
{
printf("%c ",S);
}
int LevelOrderTraverse(BiTNode *root)
{
BiTNode *p;
Linkqueue Q;
Initqueue(Q);//初始化空队列
if(root)
Enqueue(Q,root);//将根结点入队列
while(!Emptyqueue(Q))//若队列不为空
{
Dequeue(Q,p);//队头元素出列
Visit(p->data);
if(p->lchild)
Enqueue(Q,p->lchild);//队头元素有左孩子则入队
if(p->rchild)
Enqueue(Q,p->rchild);//队头元素有右孩子则入队
}
return 1;
}
int _tmain(int argc, _TCHAR* argv[])
{
BiTree Tree;
BiTNode *T;
T=CreateBiTree(Tree);
printf("
层次遍历二叉树
");
LevelOrderTraverse(T);
return 1;
}