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

来源:互联网 发布:电影语音翻译软件 编辑:程序博客网 时间:2024/06/13 14:14


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

Time Limit: 1000MS Memory Limit: 65536KB
SubmitStatistic

Problem Description

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

Input

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

Output

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

Example Input

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

Example Output

abcdefgxnuli
#include <stdio.h>#include <stdlib.h>#include <string.h>struct node{    char data;    struct node *lchild, *rchild;};char a[100];int cnt;struct node *creat(){    struct node *root;    if(a[cnt++] == ',')    {        root = NULL;    }    else    {        root = (struct node *)malloc(sizeof(struct node));        root -> data = a[cnt-1];        root -> lchild = creat();        root -> rchild = creat();    }    return root;};void cengxu(struct node *root)//层序遍历时把根节点放入,并输出根节点放入其左孩子右孩子;{    struct node *temp[100];    int in = 0, out = 0;    temp[in++] = root;    while(in > out)    {        if(temp[out])        {            printf("%c", temp[out] -> data);            temp[in++] = temp[out] -> lchild;            temp[in++] = temp[out] -> rchild;        }        out++;    }}int main(){    int t;    struct node *root;    scanf("%d", &t);    while(t--)    {        scanf("%s", a);        cnt = 0;        root = creat();        cengxu(root);        printf("\n");    }    return 0;}
阅读全文
0 0