C - 求二叉树的先序遍历

Description

 已知一棵二叉树的中序遍历和后序遍历,求二叉树的先序遍历

Input

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

Output

 输出二叉树的先序遍历序列

Sample

Input 

2
dbgeafc
dgebfca
lnixu
linux

Output 

abdegcf
xnliu

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char str1[100],str2[100];
int len;
int t;
struct node{
    struct node *lchild,*rchild;
    int date;
};
struct node*create(int len,char*str1,char*str2)
{
    struct node *root;
    root=(struct node*)malloc(sizeof(struct node));
    if(len==0)
        return NULL;
    int i;
    root->date=str2[len-1];//根节点
    for(i=0;i<len;i++)
    {
        if(str1[i]==root->date)//str2中的位置
            break;
    }
    root->lchild=create(i,str1,str2);//左子树,长度为i,i=0i=0时,返回NULL
    root->rchild=create(len-i-1,str1+i+1,str2+i);//右子树,i为str1中根节点的位置,i右边即右子树,长度为len-(i+1),即len-i-1,str1是中序序列,i的位置是根节点,所以右子树从str1+i+i开始,str2是后序序列,所以i在str2中的位置不是根节点,而是右子树的第一个节点,所以从str2+i开始,str2的根节点在str2的最后,后序遍历顺序左-右-根。
    return root;
};
void xian(struct node *root)
{
    if(root)
    {
        printf("%c",root->date);
        xian(root->lchild);
        xian(root->rchild);
    }
}
int main()
{
    scanf("%d",&t);
    for(t;t>0;t--)
    {
        scanf("%s",str1);
        scanf("%s",str2);
        len=strlen(str2);//后
        struct node *root;
        root=create(len,str1,str2);//中、后
        xian(root);
        printf("\n");
    }

}
 

可与这篇结合看(1条消息) B - 数据结构上机测试4.1:二叉树的遍历与应用1_小王同学要加油的博客-优快云博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值