暑假集训day7——数据结构实验之二叉树五:层序遍历

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

Time Limit: 1000 ms Memory Limit: 65536 KiB

Submit Statistic

Problem Description

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

Input

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

Output

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

Sample Input

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

Sample Output

abcdefg
xnuli

Hint

 

Source

xam

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int flag;
char s[1001];

struct node
{
    char data;
    struct node *l, *r;
};

struct node *creat()
{
    struct node *root;

    if(s[++flag] == ',')
    {
        root = NULL;
    }

    else
    {
        root = (struct node *)malloc(sizeof(struct node));

        root-> data = s[flag];

        root-> l = creat();
        root-> r = creat();
    }

    return root;
}

void cengxu(struct node *root)
{
   struct node *temp[1001];
   int in = 0, out = 0;

   temp[in++] = root;

   while(in > out)  
   {
       if(temp[out])
       { 
           printf("%c", temp[out]-> data);  //输出根
           temp[in++] = temp[out]-> l;    //左二子进
           temp[in++] = temp[out]-> r;   //右儿子进
       }

       out++;     //出
   }

}

int main(void)
{
    int t;
    struct node *root;

    scanf("%d", &t);
    while(t--)
    {
        scanf("%s", s);
        flag = -1;

        root = creat();

        cengxu(root);
        printf("\n");
    }

    return 0;
}
 

猜你喜欢

转载自blog.csdn.net/Eider1998/article/details/81481031