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

来源:互联网 发布:exec怎么用linux 编辑:程序博客网 时间:2024/06/07 03:19

Problem Description

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

Input

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

Output

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

Example Input

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

Example Output

abcdefgxnuli

Hint

 

Author



#include <iostream>
#include <stdlib.h>
using namespace std;


typedef struct binode
{
    char data;
    struct binode *lchild;
    struct binode *rchild;
}binode, *bitree;
char a[55];
int i;
bitree creat(bitree &T)
{
    if(a[i++] == ',')
        T = NULL;
    else
    {
        T = new binode;
        T->data = a[i - 1];
        T->lchild = creat(T->lchild);
        T->rchild = creat(T->rchild);
    }
    return T;
}
void browse(bitree T)
{
    int i = 0;
    int j = 0;
    bitree a[55];
    a[i++] = T;
    while(i > j)
    {
        if(a[j])
        {
            cout<<a[j]->data;
            if(a[j]->lchild)
                a[i++] = a[j]->lchild;
            if(a[j]->rchild)
                a[i++] = a[j]->rchild;
        }
        j++;
    }
}
int main()
{
    int n;
    cin>>n;
    while(n--)
    {
        bitree T;
        i = 0;
        cin>>a;
        T = creat(T);
        browse(T);
        cout<<endl;
    }
    return 0;
}

原创粉丝点击