数据结构实验之求二叉树后序遍历和层次遍历

这是一个数据结构实验,目标是根据给定的二叉树前序和中序遍历序列还原二叉树,并进一步输出后序遍历和层次遍历序列。题目提供了示例输入和输出,以及相关的时间和内存限制。实验要求解码算法能处理多组测试数据,每组数据包含两个字符串,分别表示前序和中序遍历序列。

think:
1通过前序遍历和中序遍历还原二叉树以及后序遍历
2 通过已还原的二叉树进行层序遍历
sdut原题链接
数据结构实验之求二叉树后序遍历和层次遍历
Time Limit: 1000MS Memory Limit: 65536KB

Problem Description
已知一棵二叉树的前序遍历和中序遍历,求二叉树的后序遍历和层序遍历。

Input
输入数据有多组,第一行是一个整数t (t<1000),代表有t组测试数据。每组包括两个长度小于50 的字符串,第一个字符串表示二叉树的先序遍历序列,第二个字符串表示二叉树的中序遍历序列。

Output
每组第一行输出二叉树的后序遍历序列,第二行输出二叉树的层次遍历序列。

Example Input
2
abdegcf
dbgeafc
xnliu
lnixu

Example Output
dgebfca
abcdefg
linux
xnuli

Hint

Author
ma6174

以下为accepted代码

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct node
{
    char date;
    struct node *left;
    struct node *right;
}BinTree;
BinTree *root, *link[54];
char st1[54], st2[54];
BinTree * get_build(int len, char *st1, char *st2)//二叉树的还原与后序遍历
{
    if(len == 0)
        return NULL;
    int i;
    BinTree *root;
    root = (BinTree *)malloc(sizeof(BinTree));
    root->date = st1[0];//寻找根节点,新的根节点为前序遍历st1的第一个
    for(i = 0; i < len; i++)//寻找新的根节点在中序遍st2中的位置
    {
        if(st2[i] == root->date)
            break;
    }
    root->left = get_build(i, st1+1, st2);//(左子树的长度,左子树在前序遍历st1中的开始位置,左子树在中序遍历st2中的开始位置)
    root->right = get_build(len-i-1, st1+i+1, st2+i+1);//(右子树的长度,右子树在前序遍历st1中的开始位置,右子树在中序遍历st2中的开始位置)
    printf("%c", root->date);//后序遍历
    return root;
}
void ans(BinTree *root)//二叉树的层序遍历
{
    if(root)///判断root是否为NULL
    {
        int i = 0, j = 0;
        link[j++] = root;
        while(i < j)
        {
            if(link[i])//判断link[i]是否为NULL
            {
                link[j++] = link[i]->left;//入队
                link[j++] = link[i]->right;//入队
                printf("%c", link[i]->date);//层序遍历
            }
            i++;//出队
        }
    }
}
int main()
{
    int T, len;
    scanf("%d", &T);
    while(T--)
    {
        scanf("%s %s", st1, st2);
        len = strlen(st1);
        root = get_build(len, st1, st2);//调用二叉树的还原与后序遍历函数
        printf("\n");
        ans(root);//调用二叉树的层序遍历函数
        printf("\n");
    }
    return 0;
}


/***************************************************
User name: jk160630
Result: Accepted
Take time: 0ms
Take Memory: 112KB
Submit time: 2017-02-08 09:14:45
****************************************************/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值