题目链接:点击打开链接
数据结构实验之二叉树五:层序遍历
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
已知一个按先序输入的字符序列,如abd,,eg,,,cf,,,(其中,表示空结点)。请建立二叉树并求二叉树的层次遍历序列。
输入
输出
示例输入
2 abd,,eg,,,cf,,, xnl,,i,,u,,
示例输出
abcdefg xnuli
提示
代码实现:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
char s[110];
int len;
struct Tree
{
char data;
Tree *lchild,*rchild;
};
Tree *T;
int i;
Tree *Creat(Tree *T)
{
if(s[i++] == ',')
T = NULL;
else
{
T = new Tree;
T->data = s[i-1];
T->lchild = Creat(T->lchild);
T->rchild = Creat(T->rchild);
}
return T;
}
void Level(Tree *T)
{
Tree *p[110];
int pu = 0,po = 0;
p[pu++] = T;
while(pu > po)
{
if(p[po])
{
printf("%c",p[po]->data);
p[pu++] = p[po]->lchild;
p[pu++] = p[po]->rchild;
}
po++;
}
}
int main()
{
int n;
while(~scanf("%d",&n))
{
while(n--)
{
Tree *P;
scanf("%s",s);
len = strlen(s);
i = 0;///注意归零
P = Creat(T);
Level(P);
printf("\n");
}
}
return 0;
}