二叉树的层次遍历--c语言实现

#include <stdio.h>
#include <stdlib.h>
/**
利用顺序存储的队列实现对二叉树的层次遍历
**/
typedef  struct  TreeNode *BinTree;
typedef BinTree ElementType ;
struct  TreeNode{
	int  data;
	BinTree  left;
	BinTree  right;
};
#define MaxSize  20
typedef  struct  {
	BinTree Data[ MaxSize ];
	int  rear;
	int  front;
} Queue;

BinTree createTreeNode(int data);//创建树
void LevelOrderTraversal ( BinTree BT );//层次遍历
void AddQ( Queue *PtrQ, ElementType item);
ElementType DeleteQ ( Queue *PtrQ );
int main()
{
    BinTree  bt1,bt2,bt3,bt4,bt5,bt6;
    bt1=createTreeNode(1);
    bt2=createTreeNode(2);
    bt3=createTreeNode(3);
    bt4=createTreeNode(4);
    bt5=createTreeNode(5);
    bt6=createTreeNode(6);
    bt1->left=bt2;
    bt1->right=bt3;
    bt2->left=bt4;
    bt2->right=bt5;
    bt3->right=bt6;
    LevelOrderTraversal ( bt1);
    return 0;
}
BinTree createTreeNode(int data)
{
	BinTree n=(BinTree)malloc(sizeof(struct  TreeNode));
	n->data = data;
	n->left = NULL;
	n->right = NULL;
	return n;
}
void LevelOrderTraversal ( BinTree BT )
{   Queue* Q=(Queue*)malloc(sizeof(Queue));
     Q->front=0;
     Q->rear=0;
    printf("队列创建成功\n");
    BinTree T;
    if ( !BT )  return; /* 若是空树则直接返回 */
    AddQ( Q, BT );
    printf("加入了根节点\n");
    while ( Q->front != Q->rear  ) {
        T = DeleteQ( Q );
        printf("%d\n", T->data); /*访问取出队列的结点*/
        if ( T->left )  AddQ( Q, T->left );
        if ( T->right )  AddQ( Q, T->right );
        }
}
void AddQ( Queue *PtrQ, ElementType item)
{
      if ( PtrQ->rear+1== MaxSize ) {
           printf("队列满");
           return;
      }
      PtrQ->rear = PtrQ->rear+1;
      PtrQ->Data[PtrQ->rear] = item;
}
ElementType DeleteQ ( Queue *PtrQ )
{
       if ( PtrQ->front == PtrQ->rear ) {
             printf("队列空");
             return NULL;
       }  else  {
            PtrQ->front = PtrQ->front+1;
            return  PtrQ->Data[PtrQ->front];
       }
}

 

    原文作者:mouthful
    原文地址: https://blog.csdn.net/mouthful/article/details/81119750
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞