• 按层次遍历二叉树-用队列作为缓冲(中等)


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

    //定义二叉树的结点
    typedef struct btnode
    {
      char data;
      struct btnode *lchild,*rchild;
    }bitree,*Bitree;

    //队列结点的定义
    typedef struct LinkQueueNode
    {
      bitree *data; //队列结点的数据域是二叉树的结点
      struct LinkQueueNode *next;
    }LKQueNode;

    //定义队列
    typedef struct LKQueue
    {
      LKQueNode *front,*rear;
    }LKQue;

    //初始化队列
    void InitQueue(LKQue *LQ)
    {
      LKQueNode *p; //定义一个队列结点的指针
      p=(LKQueNode *)malloc(sizeof(LKQueNode));//内存分配一个结点空间,由指针p指向
      LQ->front=p;
      LQ->rear=p;
      LQ->front->next=NULL; //队头指针和队尾指针都指向新结点,并将新结点的指针域置空
    }

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

    //入队操作
    void EnQueue(LKQue *LQ,Bitree x) //入队元素为二叉树的整个结点
    {
      LKQueNode *p;
      p=(LKQueNode *)malloc(sizeof(LKQueNode));
      p->data=x; //二叉树的结点是队列结点的数据域
      p->next=NULL;
      LQ->rear->next=p;
      LQ->rear=p;
    }

    //出队操作
    int OutQueue(LKQue *LQ)
    {
      LKQueNode *s;
      if(EmptyQueue(LQ))
      {
        exit(0);
        return 0;
      }
      else
      {
        s=(LQ->front)->next;
        (LQ->front)->next=s->next;
        if(s->next==NULL)
          LQ->rear=LQ->front;
        free(s);
        return 1;
      }
    }

    //取队首元素
    Bitree GetHead(LKQue *LQ) //队首结点的数据是二叉树的结点,所以要用Bitree声明函数
    { //类型
      LKQueNode *p;
      bitree *q;
      if(EmptyQueue(LQ))
        return q;
      else
      {
        p=(LQ->front)->next;
        return p->data;
      }
    }

    //创建二叉树
    Bitree CreateBinTree()
    {
      char ch;
      Bitree t;
      ch=getchar();
      if(ch == '#')
        t=NULL;
      else
      {
        t=(Bitree)malloc(sizeof(bitree)); //分配二叉树的结点
        t->data=ch;
        t->lchild=CreateBinTree();
        t->rchild=CreateBinTree();
      }
      return t;
    }

    //按层次遍历
    void LevelOrder(Bitree T)
    {
      LKQue Q;
      Bitree p;
      InitQueue(&Q);
      if(T!=NULL)
      {
        EnQueue(&Q,T);
        while(!EmptyQueue(&Q))
        {
          p=GetHead(&Q);
          OutQueue(&Q);
          printf("%c",p->data);
          if(p->lchild!=NULL)
            EnQueue(&Q,p->lchild);
          if(p->rchild!=NULL)
            EnQueue(&Q,p->rchild);
        }
      }
    }

    //主函数
    void main()
    {
      Bitree TT;
      printf("按先序序列输入结点序列,‘#’代表空。 ");
      printf("例如:ABD#C##E##G#FH### ");
      TT=CreateBinTree();
      printf("层次遍历序列为: ");
      LevelOrder(TT);
      printf(" ");
    }

    运行结果:

  • 相关阅读:
    JS日期比较,使用正则表达式转换
    Using SQL*Loader to create an external table
    USACO试题beads的两种解法
    activiti5学习资料(5.12版本流程图的生成)
    黑马程序员_day20_Map集合
    开发者使用JasperReport——不同数据源之Map数据源
    给自己科谱:控制字符
    507 Jill Rides Again
    探讨工作流能给公司带来的几点益处
    ubuntu linux安装双系统的方法Win7、XP下均可
  • 原文地址:https://www.cnblogs.com/duanqibo/p/11295282.html
Copyright © 2020-2023  润新知