数据结构——二叉树的层次遍历

二叉树的层次遍历

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#define OK      1
#define TRUE    1
#define FALSE   0
#define ERROR   0

typedef struct Node{        //二叉树的链式存储结点 
	char data;
	struct Node *Lchild;
	struct Node *Rchild;
}BiTNode,*BiTree;

//先序遍历的递归算法创建二叉树的存储
void CreateBiTree(BiTree *root){      //形参采用二级指针,实参为结点孩子域地址 
	char ch;
	ch=getchar();
	
	if(ch=='#')    *root=NULL;
	else{
		*root=(BiTree)malloc(sizeof(BiTree));
	    (*root)->data=ch; 
	    CreateBiTree(&((*root)->Lchild));
	    CreateBiTree(&((*root)->Rchild));
	}
} 

void Visit(char data){
	printf("%c",data);
}

/********队列函数*******/
 typedef struct array{      //定义队列结构 
 	BiTree elem;
 	struct array *next;
 }*PLArray; 
 
 typedef struct Node_D{
 	PLArray  front;   //指向队头 
 	PLArray  rear;    //指向队尾 
 	int len;          //队列实际长度 
 }*pNode;
void InitArray(pNode &S){    //构造空队列 
	PLArray q=(PLArray)malloc(sizeof(PLArray)); //申请新结点
	S=(pNode)malloc(sizeof(pNode)); 
	S->front=q;
	S->rear=q;
	S->front->next=NULL;
	S->len=0; 
	
}

int Push(pNode &S,BiTree e){    //插入数据e为队列的队尾 
	PLArray p=(PLArray)malloc(sizeof(PLArray));  //申请新结点 
	p->elem=e;
	
	p->next=NULL;
	S->rear->next=p;   //将结点插入到队尾 
	S->rear=p;         //修改队尾指针 
	S->len++; 
}

int Pop(pNode &S,BiTree &e){    //删除队头元素,,用e返回其删除数据 
	if(S->front==S->rear)  return FALSE;
	PLArray p=S->front->next;   //p指向队头
	e=p->elem;
	S->front->next=p->next;   //修改头结点的指针域
	if(S->rear==p) S->rear=S->front;   //最后元素被删除
	S->len--;
	return OK ;
}

int ArrayEmpty(pNode &S){    //判断队列是否为空 
	if(S->len==0)  return TRUE;
	else           return FALSE;
} 

int Refer(pNode &S,BiTree &e) {  //查询队头元素 
	e=S->front->next->elem;
}

void LevelOrder(BiTree T){   //层次遍历    
     pNode S;
     InitArray(S);
     BiTree p;
     Push(S,T);
     while(!ArrayEmpty(S)){
     	Pop(S,p);
     	Visit(p->data);
     	if(p->Lchild!=NULL)
     	    Push(S,p->Lchild);
     	if(p->Rchild!=NULL)
		    Push(S,p->Rchild);    
	 }
} 

int main(){
	BiTree T;
	CreateBiTree(&T);
	LevelOrder(T);
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/qq_41596568/article/details/84327961