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

来源:互联网 发布:ubuntu install opera 编辑:程序博客网 时间:2024/06/07 02:53

数据结构实验之二叉树五:层序遍历
Time Limit: 1000MS Memory Limit: 65536KB
Submit Statistic
Problem Description

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

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

输出二叉树的层次遍历序列。
Example Input

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

abcdefg
xnuli
Hint

Author

最重要的还是理解。。。。

#include<stdio.h>#include<stdlib.h>char a[55];int top;struct tree{    int data;    struct tree *l, *r;};struct tree *creat(){    struct tree *root;    top++;    if(a[top] == ',')        root = NULL;    else    {        root = (struct tree*) malloc (sizeof(struct tree));        root -> data = a[top];        root -> l = creat();        root -> r = creat();    }    return root;};void cengxu(struct tree *root){    int in = 0, out = 0;    struct tree *p[100]; //用来存放每一层的数据    p[in] = root;    in++;    while(in > out) //控制循环跳出    {        if(p[out])//防止超时,当时空节点时直接到下一个        {            printf("%c", p[out] -> data);//输出当前节点            p[in] = p[out] -> l;//把当前输出数据的左右节点保存            in++;            p[in] = p[out] -> r;            in++;        }        out++;//注意一直输出的是p[out] -> data    }}int main(){    int t;    struct tree *root;    scanf("%d", &t);    while(t--)    {        top = -1;        scanf("%s", a);        root = creat();        cengxu(root);        printf("\n");    }    return 0;}
0 0