二叉树的层次遍历

 
#include "stdio.h"
#include "stdlib.h"
#include "1.h"
#define MAXSIZE 100
#define TRUE 1
#define FALSE 0
#define OVERFLOW -1
#define OK 1
#define ERROR 0
typedef int status;
typedef  char TElemType;
typedef struct BiTNode{  //二叉链表的定义
	 TElemType    data;
	 struct BiTNode *lchild,*rchild;
	} BiTNode, *BiTree;
typedef BiTree QElemType;
typedef struct
	{
	QElemType* base;
	int front;
	int rear;
	}SqQueue;//循环队列的定义

//初始化
status InitQueue(SqQueue &Q)
{
	Q.base=(QElemType*)malloc(MAXSIZE *sizeof(QElemType));
	if(!Q.base)
		exit(OVERFLOW);
	Q.front=0 ;
	Q.rear=0;
	return OK;
}

//判断队空
status QueueEmpty(SqQueue Q)
{
	if(Q.rear==Q.front)
		return TRUE;
	else  
		return FALSE;
}

//取对头元素
status GetHead(SqQueue Q,QElemType &e)
{
	if(QueueEmpty(Q))
		return ERROR;
	else
		return (Q.front);
	return OK;
}

//求队列长度
int QueueLength(SqQueue Q)
{
	return(Q.rear-Q.front+MAXSIZE)%MAXSIZE;
}

//入队操作
status EnQueue(SqQueue &Q,QElemType e)
{
	if(Q.front==(Q.rear+1)%MAXSIZE)
		return ERROR;//队列满
     Q.base[Q.rear] = e;
	Q.rear=(Q.rear+1)%MAXSIZE;
	return OK;
}

//出队操作
status DeQueue(SqQueue &Q,QElemType &e)
{
	if(Q.front==Q.rear)
		return ERROR;//队列空
	e=Q.base[Q.front];
	Q.front=(Q.front+1)%MAXSIZE;
	return OK;
}
/*
	下面的是对树的操作
  */
//D.FH...E.G..C..
void createBigTree (BiTree &bt) {
	char ch ;
	ch = getchar();
	if (ch == '#') {
		bt = NULL;
	}else {
		
		bt = (BiTree)malloc(sizeof(BiTNode));
		bt->data = ch;
		createBigTree(bt->lchild);
		createBigTree (bt->rchild);
	}
	
}

void print(BiTree bt) {
	if (bt!=NULL) {
		printf("%c ",bt->data);
		print(bt->lchild);
		print(bt->rchild);
	}	

}

/*层次遍历
//其思想的核心是使用相应的队列的特点:
// a
  / \
 b   c
 /\
e  f
相应的结果应该:a->b->c->e->f;
*/

void divPrint (BiTree bt) {
	SqQueue queue;//队列
	InitQueue(queue);
	EnQueue(queue,bt);
	QElemType e = NULL;
	while (!QueueEmpty(queue)) {
		DeQueue(queue,e);
		printf("%c ",e->data);
		if (e->lchild!= NULL) {	
		EnQueue(queue,e->lchild);
		}
		if (e->rchild!=NULL) {
			EnQueue(queue,e->rchild);
		}
	}
}

void main () {
	BiTree tree;
	createBigTree(tree);
	divPrint(tree);
}

输入:abe##f##c##
输出:
a b c e f

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值