E - 求二叉树的层次遍历

Description

已知一颗二叉树的前序遍历和中序遍历,求二叉树的层次遍历。

Input

输入数据有多组,输入T,代表有T组测试数据。每组数据有两个长度小于50的字符串,第一个字符串为前序遍历,第二个为中序遍历。

Output

每组输出这颗二叉树的层次遍历。

Sample

Input

2
abc
bac
abdec
dbeac

Output

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

struct node{
    char c;// 储存字符
    struct node *lt, *rt;// 左右节点
};
char pre[50];// 前序
char in[50];// 中序
int len;
struct node *create(int len, char pre[], char in[]){/* 根据前序中序建立二叉树*/
    struct node *root;
    if(!len){// 如果长度为零,则不能建树
        root = NULL;
        return root;
    }
    root = (struct node *)malloc(sizeof(struct node));// 申请新的节点
    root -> c = pre[0];// 前序的顺序第一个一定是根节点
    int i;
    for(i = 0; i < len; i++){// 寻找中序中到根节点,即现在的这颗树的所有左子树
        if(pre[0] == in[i]){
            break;// 找到跳出循环
        }
    }
    root -> lt = create(i, pre + 1, in);// 建左子树
    root -> rt = create(len - 1 - i, pre + 1 + i, in + 1 + i);// 建右子树
    return root;// 返回根节点。
}
void hierarchical(struct node *root){/* 层次遍历*/
    if(root){
        int in = 0, out = 0;
        struct node *hie[50];
        hie[in++] = root;
        while(out < in){
            if(hie[out]){
                printf("%c", hie[out] -> c);
                hie[in++] = hie[out] -> lt;// 左子树
                hie[in++] = hie[out] -> rt;// 右子树
            }
            out++;
        }
    }
}
int main(){
    int t, i;
    scanf("%d", &t);
    for(i = 0; i < t; i++){
        scanf("%s", pre);
        scanf("%s", in);
        len = strlen(pre);
        struct node *root;
        root = create(len, pre, in);
        hierarchical(root);
        printf("\n");
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员豪仔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值