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

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

                                                                                 Time Limit: 1000MS Memory Limit: 65536KB

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

#include <iostream>
#include <stdio.h>
char str[123456];
int g=0,t=0;
using namespace std;
typedef struct BitTree
{
    int data;
    BitTree *rchild,*lchild;
}Tree;
Tree *creat(Tree *p)
{
    char c;
    c = str[g++];
    if(c==','||c=='\0')
    {
        return NULL;
    }
    else
    {
        p = new Tree;
        p->data = c;
        p->lchild = creat(p->lchild);
        p->rchild = creat(p->rchild);

    }
    return p;
}
void sequence(Tree *root)
{
    int out=0,in=0;
    BitTree *q[100];
    q[in++] = root;
    while(in>out)
    {
        if(q[out])
        {
            printf("%c",q[out]->data);
            q[in++] = q[out]->lchild;
            q[in++] = q[out]->rchild;
        }
        out++;
    }

}
int main()
{
    int N;
    scanf("%d",&N);
    while(N--)
    {   scanf("%s",str);
        g=0;
        Tree *root;
        root = creat(root);
        sequence(root);
        printf("\n");
    }
    return 0;
}



posted @ 2016-10-25 22:29  Philtell  阅读(279)  评论(0编辑  收藏  举报