您的位置:首页 > 理论基础 > 数据结构算法

数据结构实验之二叉树五:层序遍历

2017-11-01 15:27 239 查看


Problem Description

已知一个按先序输入的字符序列,如abd,,eg,,,cf,,,(其中,表示空结点)。请建立二叉树并求二叉树的层次遍历序列。


Input

 输入数据有多行,第一行是一个整数t (t<1000),代表有t行测试数据。每行是一个长度小于50个字符的字符串。


Output

 输出二叉树的层次遍历序列。
#include <stdio.h>
#include <stdlib.h>

typedef struct node
{
char data;
struct node *lc;
struct node *rc;
} BiTree;

int i;

BiTree *Creat(char s[])
{
BiTree *T;
if(s[++i] != ',')
{
T = (BiTree*)malloc(sizeof(BiTree));
T->data = s[i];
T->lc = Creat(s);
T->rc = Creat(s);
}
else
T = NULL;
return T;
}
/*建立数组,先存入根节点,输出根节点的同时存入左右孩子。如此循环直到遍历完成*/
void Travel(BiTree *T)
{
BiTree *temp[100];
int in = 0, out = 0;
temp[in++] = T;
while(in > out)
{
if(temp[out])
{
printf("%c", temp[out]->data);
temp[in++] = temp[out]->lc;
temp[in++] = temp[out]->rc;
}
out++;
}
}

int main()
{
int t;
BiTree *T;
char s[100];
scanf("%d", &t);
while(t--)
{
scanf("%s", s);
i = -1;
T = Creat(s);
Travel(T);
printf("\n");
}
return 0;
}



Example Input

2
abd,,eg,,,cf,,,
xnl,,i,,u,,



Example Output

abcdefg
xnuli
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: