本题要求实现给定的二叉树的层次遍历。
函数接口定义:void Levelorder(BiTree T);
T是二叉树树根指针,Levelorder函数输出给定二叉树的层次遍历序列,格式为一个空格跟着一个字符。
其中BinTree结构定义如下:
typedef char ElemType;
typedef struct BiTNode
{
ElemType data;
struct BiTNode *lchild, *rchild;
}BiTNode, *BiTree;
输入样例:
输入为由字母和'#'组成的字符串,代表二叉树的扩展先序序列。例如对于如下二叉树,输入数据:
AB#DF##G##C##
输出样例(对于图中给出的树):
Levelorder: A B C D F G
void Levelorder(BiTree T)
{
BiTree q[100];
int f=0,r=0;
if(T)
q[r++]=T;//入队列
while(f!=r)
{
BiTree now=q[f++];//出队列
printf(" %c",now->data);
if(now->lchild) //左子树,不空入队列
q[r++]=now->lchild;
if(now->rchild)//右子树,不空入队列
q[r++]=now->rchild;
}
}