zoukankan      html  css  js  c++  java
  • 按层次遍历二叉树-用队列作为缓冲(中等)

    #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(" ");
    }

    运行结果:

  • 相关阅读:
    关于grunt
    关于网页上标题图标显示
    form表单原理
    js判断是android访问还是ios访问
    判断客户端是手机访问还是电脑访问网站(php代码)
    电脑手机模拟器模拟手机浏览器,在线浏览手机网站
    手机网站通过JS判断是否为iPhone手机访问
    手机页面一键拨号
    html5手机网站常用的9个CSS属性
    js解析与序列化json数据(一)json.stringify()的基本用法
  • 原文地址:https://www.cnblogs.com/duanqibo/p/11295282.html
Copyright © 2011-2022 走看看