层次遍历2叉树

/************************************
--修改日期:	2009.5.26
--修改人:	           吴强
--修改原因:	从前写的代码不够规范
--输入要求:	先序遍历顺序输入各节点,‘.’号为空节点
		例子:ABD...CE.G..F..
************************************/
#include 
#include 
#include 
#include 

#define MAX 50

//链式二叉树结构
typedef struct Btree	
{
    char	cData;
    struct Btree	*pLchild;
    struct Btree	*pRchild;
}BTree;

//静态队列,实现二叉树层次遍历
typedef struct Queue	
{
    BTree	queData[MAX];
    int		front;
    int		rear;
}QueueNode;

//构造空二叉树
BTree *InitBtree()		
{
    BTree	*root;
    root= NULL;
    return	root;
}

//构造空队列
QueueNode *InitQueue()
{
    QueueNode *queue;

    queue= (QueueNode *)malloc( sizeof(QueueNode) );
    queue->front= queue->rear= 0;

    return queue;
}

//建立二叉树,先序遍历输入各节点
void CreateBtree(BTree **root)
{
    char c;
	
    c= getchar();
	
    if ( c == '.' )	//输入'.'则表示节点为空
    {
	*root=NULL;
    }
    else
    {
	*root= (BTree *)malloc( sizeof(BTree) );

	(*root)->cData= c;
	CreateBtree( &((*root)->pLchild) );
	CreateBtree( &((*root)->pRchild) );
    }
}

//入队操作
int Push(QueueNode *s, BTree *Bnode)
{
    //判断队列是否满
    if ( (s->rear+1)%MAX == s->front )
    {
	printf("Queue full!/n");
	return 0;
    }
    else
    {
	s->queData[s->rear]= *Bnode;
	s->rear= ( s->rear+1 )%MAX;

	return 1;
    }
}

//出队操作
int Pop(QueueNode *s)
{
    //判断队列是否以为空
    if ( s->front == s->rear )
    {
        printf("Queue null!/n");
        return 0;
    }
    else
    {
        s->front= ( s->front+1 )%MAX;
        return 1;
    }
}

//读队列头元素
BTree *GetFront(QueueNode *s)
{
    //判断队列是否以为空
    if ( s->front == s->rear )
    {
    	printf("Stack null!/n");
    	return 0;
    }
    else
    {
    	return &( s->queData[s->front] );
    }
}

//判断队列是否为空
int IsEmptyQueue(QueueNode *q)
{
    if ( q->front == q->rear )
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

main()
{
    BTree *Broot;	//储存整棵二叉树
    BTree *node;	//读取队列元素的暂存变量
    QueueNode *Queue;	
    
    Broot= InitBtree();
    Queue= InitQueue();
    
    //建立二叉树
    CreateBtree(&Broot); 
    Push(Queue,Broot);
    
    //清屏
    //clrscr();
    
    //层次遍历输出二叉树的实现
    while( !IsEmptyQueue(Queue) )
    {
    	node= GetFront(Queue);
    	printf("%c",node->cData);
		
    	if ( node->pLchild!= NULL )
	{
    	    Push( Queue,node->pLchild );
    	}
	  		
    	if ( node->pRchild!= NULL )
	{
    	    Push( Queue,node->pRchild );
	}	
	   		
    	Pop(Queue);
    }

    print("/n");
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值