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

来源:互联网 发布:开农村淘宝靠什么赚钱 编辑:程序博客网 时间:2024/06/12 21:14

Problem Description

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

Input

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

Output

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

Example Input

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

Example Output

abcdefgxnuli


代码:

#include <bits/stdc++.h>
#include <string.h>
using namespace std;
int cnt, k, n;
char a[51], b[51];
struct node
{
    char data;
    struct node *l, *r;
};
struct node *create()
{
    struct node *root;
    root=(struct node*)malloc(sizeof(struct node));
    if(a[++cnt]==',')
        root = NULL;
    else
    {
        if(a[cnt])
        {
            root->data = a[cnt];
            root->l = create();
            root->r = create();
        }
    }
    return root;
}
void shuchu(struct node *root)                   //用一个结构体数组,保存输出结点,每输出一个结点就把该结点的左孩子和右孩子保存在数组的最后。
{
    int in=0, out=0;
    struct node *a[100];
    a[in++] = root;
    while(in>out)
    {
        if(a[out])
        {
            cout << a[out]->data;
            a[in++]=a[out]->l;
            a[in++]=a[out]->r;
        }
        out++;
    }
}
int main()
{
    int t;
    while(~scanf("%d", &t))
    {
        while(t--)
        {
            scanf("%s", a);
            struct node *root;
            cnt = -1;
            root = create();
            shuchu(root);
            cout << endl;
        }
    }
    return 0;
}

阅读全文
0 0
原创粉丝点击