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

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

Time Limit: 1000 ms Memory Limit: 65536 KiB

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

PS:如果对二叉树的遍历没有了解的话请先看我的另一篇博客 二叉树的四种遍历方式

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct tree
{
    char data;
    struct tree *l,*r;
}tree;

int i;
char s[55];

tree *newtree()
{
    tree *t;
    t = (tree*)malloc(sizeof(tree));
    t->l = t->r = NULL;
    return t;
}

tree *creat() //根据所给的遍历顺序建树
{
    tree *t = newtree();
    if(s[i++]==',')
        return NULL;
    t->data = s[i-1];
    t->l = creat();
    t->r = creat();
    return t;
}

void show(tree *t) //层序遍历
{
    tree *q[55],*t1;  //q[]来模拟队列
    int front,base;  //队列的首和尾
    front = base = 0;
    if(t)
    {
        q[base++] = t;
    }
    while(front!=base) //当队首与队尾相等时队伍为空
    {
        t1 = q[front++];
        printf("%c",t1->data);
        if(t1->l)
            q[base++] = t1->l;
        if(t1->r)
            q[base++] = t1->r;
    }
}

int main()
{
    tree *t;
    int k;
    scanf("%d",&k);
    while(k--)
    {
        scanf("%s",s);
        i = 0;
        t = newtree();
        t = creat();
        show(t);
        printf("\n");
    }
    return 0;
}

posted @   洛沐辰  阅读(571)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示