首页 > 学院 > 开发设计 > 正文

求二叉树的先序遍历

2019-11-11 04:15:46
字体:
来源:转载
供稿:网友

PRoblem Description

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

Input

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

Output

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

Example Input

2dbgeafcdgebfcalnixulinux

Example Output

abdegcfxnliu
 
#include<stdio.h>#include<string.h>#include<stdlib.h>typedef struct node{    char data;    struct node *lc,*rc;}bitree;bitree * create(int zlen,char hst[51],char zst[51]){    int i;    bitree *t;    if(zlen<=0)        return NULL;    t=(bitree *)malloc(sizeof(bitree));    t->data=hst[0];    for(i=0;i<zlen;i++)    {        if(zst[i]==hst[0])            break;    }    t->lc=create(i,hst-zlen+i,zst);    t->rc=create(zlen-i-1,hst-1,zst+i+1);    return t;}void preshow(bitree * tree){    bitree * t;    t=tree;    if(t)    {        printf("%c",t->data);        preshow(t->lc);        preshow(t->rc);    }}int main(){    int t,zlen,hlen;    char hst[51],zst[51];    bitree * tree;    scanf("%d",&t);    while(t--)    {        scanf("%s%s",zst,hst);        zlen=strlen(zst);        hlen=strlen(hst);        tree=create(zlen,hst+hlen-1,zst);        preshow(tree);        printf("/n");    }    return 0;}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表