69,373
社区成员
发帖
与我相关
我的任务
分享
void Levelorder(BinTree T)
{/*按层次遍历二叉树T*/
int i,j;
BinTNode *q[20],*p; /*q[20]用于模拟队列,存储入队的结点*/
p=T;
if(p!=NULL)
{
i=1;q[i]=p;j=2;
} /*i为队首位置,j为队尾位置*/
while(i!=j)
{
p=q[i];
printf("%3c",p->data); /*访问队首元素*/
if (p->lchild!=NULL)
{
q[j]=p->lchild;
j++;
}
/*若队首元素左链域不为空,则将其入队列*/
if (p->rchild!=NULL)
{
q[j]=p->rchild;
j++;
}
/*若队首元素右链域不为空,则将其入队列*/
i++; /*将队首移到下一个位置*/
}
}
//二叉树层次遍历
<template<class T>
void LevelOrder(BinaryTreeNode<T> *t)
{
LinkedQueue<BinaryTreeNode<T>* > Q;
while(t)
{
Visit(t);
if(t->LeftChild)
Q.Add(t->LeftChild);
if(t->RightChild)
Q.Add(t->RightChild);
try{Q.Delete(t);}
catch(OutOfBounds){return;}
}
}
//二叉树层次遍历算法
#include <stdio.h>
#include <alloc.h>
#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)
{
case 1:St[top]->lchild=p;break;
case 2: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");
}
return 0;
}