数据结构实验之二叉树五:层序遍历(用c++stl 的queue完成的)

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

AC代码

#include <bits/stdc++.h>

using namespace std;
struct node
{
    char data;
    struct node *lson;
    struct node *rson;
};
queue<node *>q;//**队列的类型是结构体指针**
char s[55];
int i;
struct node *creat(struct node *t)
{
    if(s[i]==',')
    {
        t=NULL;
        i++;
    }
    else
    {
        t=(struct node *)malloc(sizeof(struct node));
        t->data=s[i++];
        t->lson=creat(t->lson);
        t->rson=creat(t->rson);

    }
    return t;
}
void show(struct node *t)//队列的层次遍历
{
    if(t!=NULL)
    q.push(t);
    while(!q.empty())//循环输出
    {
        struct node *now=q.front();
        q.pop();
        cout<<now->data;
        if(now->lson!=NULL)
            q.push(now->lson);
        if(now->rson!=NULL)
            q.push(now->rson);
    }
}
int main()
{
    int n;
    scanf("%d",&n);
    struct node *t;
    while(n--)
    {
        i=0;
        scanf("%s",s);
        t=creat(t);
        show(t);
        printf("\n");
    }
    return 0;
}
发布了90 篇原创文章 · 获赞 18 · 访问量 3354

猜你喜欢

转载自blog.csdn.net/sherry_zhen/article/details/103941015