二叉树采用二叉链表结构表示。设计并实现如下算法:输入某棵二叉树的广义表形式,建立该二叉树,并按层次遍历该二叉树。

来源:互联网 发布:中国隐形富豪知乎 编辑:程序博客网 时间:2024/06/08 12:26

掌握二叉树的二叉链表存储结构;掌握二叉树的遍历规则;利用二叉树的二叉链表存储结构实现二叉树的建树操作;利用二叉树的二叉链表存储结构实现二叉树层次遍历操作

二叉树采用二叉链表结构表示。设计并实现如下算法:输入某棵二叉树的广义表形式,建立该二叉树,并按层次遍历该二叉树----队列形式

 

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define STACK_MAX_SIZE 30
#define QUEUE_MAX_SIZE 30


typedef struct BitNode{
char data;
struct BitNode *lchild;
struct BitNode *rchild;
}BitNode,*BiTree;;

typedef struct node
{
  BitNode *data;
}node,*queue;

typedef struct Queue
{ node *base;
  int front;
  int rear;
}Queue;

void InitQueue(Queue *Q)
 {  Q->base=(queue)malloc(QUEUE_MAX_SIZE*sizeof(node));
    Q->front=Q->rear=0;
  }

 int  EmptyQueue(Queue *Q)
   {   if(Q->front==Q->rear)
        return 1;
        else
        return 0;
    }

void EnQueue(Queue *Q,BitNode *e)
  {  Q->base[Q->rear].data=e;
    Q->rear++;
   }

BiTree DeQueue(Queue *Q)
{
   int m;
   m=Q->front;
   Q->front++;
   return (Q->base[m].data);
 }
char a[50];

BiTree CreatBiTree(BiTree T)
{

BiTree p;
BiTree s[STACK_MAX_SIZE];
int top = -1;
int flag;
int i = 0;
T=NULL;
while(a[i]!='#')
{
switch(a[i])
{case' ':break;
case '(':
          top++;
         s[top] = p;
          flag = 1;
          break;
case ')':
          top--;
          break;
case ',': flag = 0; break;
default: p = (BitNode *)malloc(sizeof(BitNode));
         p->data = a[i];
         p->lchild = p->rchild = NULL;
         if(T==NULL)
         { T=p; }
         else
         { if( flag == 1)
           { s[top]->lchild = p; }
           else { s[top]->rchild = p; }
         }
}
i++;
}
 return T;
 }

void LevelOrder(BiTree T)
{  Queue l;

Queue *Q=&l;
  BiTree p;
  InitQueue(Q);
  if(T)
  {EnQueue(Q,T);
  while(!EmptyQueue(Q))
   {  p=DeQueue(Q);
       printf("%c",p->data);
       if(p->lchild)
        EnQueue(Q,p->lchild);
       if(p->rchild)
        EnQueue(Q,p->rchild);
    }
   }
}

void main()
{
    BitNode *T;
    printf("please input the Generalized list: \n");
    gets(a);
   T=CreatBiTree(T);
   printf("the order is:\n");
   LevelOrder(T);
   getch();
}


 

原创粉丝点击