二叉树层次遍历算法

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

//二叉树层次遍历算法

#include

#include

#define MaxSize 1000

typedef char ElemType;

typedef struct node

{

ElemType data;

struct node *lchild;

struct node *rchild;

} BTNode;

//创建二叉树

void CreateBTNode(BTNode *&b,char *str)

{

BTNode *St[MaxSize],*p=NULL;

int top=-1,k,j=0;

char ch;

b=NULL;

ch=str[j];

while(ch!='\0')

{

switch(ch)

{

case'(':top++;St[top]=p;k=1;break;

case')':top--;break;

case',':k=2;break;

default:p=(BTNode *)malloc(sizeof(BTNode)); p->data=ch;p->lchild=p->rchild=NULL;

if(b==NULL) b=p;

else

{

switch(k)

{

case1:St[top]->lchild=p;break;

case2:St[top]->rchild=p;break; }

}

}

j++;

ch=str[j];

}

}

//层次遍历算法

void LevelOrder(BTNode *b)

{

BTNode *p;

BTNode *qu[MaxSize];

int front,rear;

front=rear=-1;

rear++;

qu[rear]=b;

while(front!=rear)

{

front=(front+1)%MaxSize;

p=qu[front];

printf("%c ",p->data);

if(p->lchild!=NULL)

{

rear=(rear+1)%MaxSize;

qu[rear]=p->lchild;

}

if(p->rchild!=NULL)

{

rear=(rear+1)%MaxSize;

qu[rear]=p->rchild;

}

}

}

//主函数

int main()

{

BTNode *b,*h;

char s[MaxSize];//A(B(D(,G)),C(E,F)) printf("请输入二叉树括号表示法字符串:\n");

while(scanf("%s",&s))

{

CreateBTNode(b,s);

printf("层次遍历算法的访问次序为:");

LevelOrder(b);

printf("\n请输入二叉树括号表示法字符串:\n");

}

return0;

}

相关文档
最新文档