#include<stdio.h>
#include<assert.h>
#define QUEUESIZE 8
#define INC 2 //增量为2
typedef int QueueElem
//第一种结构体 //放入头文件queue.h中
typedef int ElemType;
/*typedef struct
{
ElemType data[MAXSIZE]; //数组类型
int front; //头
int tail //尾
}Queue;*/
//第二种结构体
typedef struct
{
ElemType *data; //指针类型
int front; //头
int tail; //尾
int maxsize; //最大空间
int cuisize; //当前位置
}Queue;
//队列的初始化
void Init_Queue(Queue *pe)
{
assert(pe!=NULL);
pe->front =0;
pe->tail =0;
pe->cursize =0;
pe->maxsize =QUEUESIZE;
pe->data =(QueueElem*)malloc(size(QueueElem)*pe->maxsize );
}
//摧毁队列
void Destry_Queue(Queue *pe)
{
assert(pe!=NULL);
free(pe->data );
pe->data =NULL;
pe->maxsize =0;
pe->front =0;
pe->tail =0;
pe->cursize =0;
}
//判断队列为空
bool empty(Queue *pe)
{
assert(pe!=NULL);
return (Queue_size(pe)==0);
}
//满队列
bool full_queue(Queue *p)
{
assert(p != NULL);
return(size_queue(p) == p->maxsize);
}
//入队列
void Queue_push(Queue *pe,QueueElem x)
{
assert(pe!=NULL);
if(Queue_full(pe))
{
//IncQueue
}
pe->data [pe->tail ]=x;
pe->tail =(pe->tail +1)%pe->maxsize ;
}
front();//top 对头(删除元素)
//返回队列头
ElemType queue_front(Queue *p)
{
assert(p != NULL);
return p->front;
}
//返回队列尾(插入元素)
ElemType queue_tail(Queue *p)
{
assert(p != NULL);
int cur = p
return p->tail;
}
//队列当前大小
int size_queue(Queue *p,ElemType value)
{
assert(p != NULL);
return p->cuisize;
}
//线索化二叉树结构体:
typedef char ElemType;
typedef enum{LINK = 0,THREAD = 1}PointTag;
typedef struct BiThrNode
{
BiThrNode *leftchild;
BiThrNode *rightchild;
PointTag Ltag,Rtag; //枚举
ElemType data;
}BiThrNode * ThreadBinaryTree;
//层次遍历二叉树 用队列解决
void LevelOrder(BtNode *ptr)
{
if (ptr == NULL)
{
return;
}
Queue q;
init_queue(&q);
push_queue(&q,ptr); //将ptr的值赋予队列
while(!empty_queue(&q))
{
ptr = queue_front(&q); //将队列头的值给ptr
pop_queue(&q); //出队列
printf("%c ",ptr->data); //打印ptr的值
if (ptr->leftchild != NULL)
{
push_queue(&q,ptr->leftchild); //把左子树的值给队列
}
if (ptr->rightchild != NULL)
{
push_queue(&q,ptr->rightchild); //把右子树的值给队列
}
}
destroy_queue(&q); //摧毁二叉树
}
//打印二叉树的第k层元素 不用队列解决
void printfK(BtNode *ptr,int k)
{
if (ptr == NULL || k == 0)
{
printf() ptr->data;
return;
}
if (ptr->leftchild != NULL)
{
printfK(ptr->leftchild,k-1); //递归解决
}
if (ptr->rightchild != NULL)
{
printfK(ptr->rightchild,k-1); //右子树递归
}
}
void print_KLevelData(BtNode *ptr,int k) //打印第k层元素
{
if (ptr == NULL || k<0)
{
return;
}
printfK(ptr,k); //函数
}
二叉树的层次遍历
于 2017-09-23 23:03:24 首次发布