#include <stdio.h> #include <stdlib.h> typedef struct BTNode{ char data; struct BTNode *lchild,*rchild; }BTNode,*BiTree; #define MAX 100 typedef struct CQueue{ BiTree *base; int front; int rear; }CQueue; void InitQueue(CQueue &q){ //初始化一个队列 q.base = (BiTree *)malloc(sizeof(BiTree) * MAX); if(!q.base) exit(0); q.front = q.rear = 0; }//InitQueue void EnQueue(CQueue &q,BiTree bt){ //数据进队 if( ((q.rear + 1)%MAX) == q.front) exit(0); q.base[q.rear] = bt; q.rear = (q.rear + 1)%MAX; }//EnQueue int QueueEmpty(CQueue q){ //判断是否为空 return q.front == q.rear? 1:0; } void DeQueue(CQueue &q,BiTree &bt){ //出队列 if(QueueEmpty(q)) exit(0); bt = q.base[q.front]; q.front = (q.front +1 )%MAX; }//DeQueue void CreatBiTree(BiTree &bt,char Data[],int n){ //③ 将一棵二叉树的所有结点存储在一维数组中,虚结点用#表示, //利用二叉树的性质5,建立二叉树的二叉链表。 //例如用数组a存储的二叉树的结点如下(0单元不用): CQueue Q; int Qn[MAX],f,r,i; BiTree p; if(n<1){ bt = NULL; return; } bt = (BiTree)malloc(sizeof(BTNode)); bt ->data = Data[1]; InitQueue(Q); EnQueue(Q,bt); f = r = 0; Qn[r++]=1; while(!QueueEmpty(Q)){ DeQueue(Q,p); i=Qn[f++]; if(2*i > n || Data[2*i] == '#') p->lchild = NULL; else{ p->lchild = (BiTree)malloc(sizeof(BTNode)); p->lchild->data = Data[2*i]; EnQueue(Q,p->lchild); Qn[r++] = 2*i; } if(2*i+1 > n || Data[2*i+1] == '#') p->rchild = NULL; else{ p->rchild = (BiTree)malloc(sizeof(BTNode)); p->rchild->data = Data[2*i+1]; EnQueue(Q,p->rchild); Qn[r++] = 2*i+1; } } } void PreOrderTraverse1(BiTree bt){ if(bt){ printf("%3c",bt->data); PreOrderTraverse1(bt->lchild); PreOrderTraverse1(bt->rchild); } } void main(){ BiTree bt; int n; scanf("%d",&n); CreatBiTree(bt,"#ABC#D#E",n);//结点个数为字符串个数减一 PreOrderTraverse1(bt); }