求二叉树的先序遍历

来源:互联网 发布:vivo授权网络怎么弄 编辑:程序博客网 时间:2024/04/30 14:59

求二叉树的先序遍历

Time Limit: 1000ms   Memory limit: 65536K  有疑问?点这里^_^

题目描述

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

输入

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

输出

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

示例输入

2dbgeafcdgebfcalnixulinux

示例输出

abdegcfxnliu

提示

 

来源

 GYX

示例程序

#include <stdio.h>#include <string.h>#include <stdlib.h>struct node{    char data;    struct node *left,*right;};struct node *root;struct node *creat(int n,char *str1,char *str2){    int i;    if(n==0)        return NULL;    root=(struct node *)malloc(sizeof(struct node));    root->data=str2[n-1];//找到根节点    for(i=0;i<n;i++)//找到str1中的根节点的位置    {        if(str1[i]==str2[n-1])            break;    }    printf("%c",root->data);//输出头结点    root->left=creat(i,str1,str2);//(左子树的长度,str1中左子树开始位置的地址,str2中左子树开始位置的地址)      root->right=creat(n-i-1,str1+i+1,str2+i);//(右子树的长度,str1中右子树开始位置的地址,str2中右子树开始位置的地址)    return root;};int main(){    int n;    char str1[110],str2[110];    scanf("%d",&n);    while(n--)    {        scanf("%s",str1);        scanf("%s",str2);        int len=strlen(str1);        creat(len,str1,str2);        printf("\n");    }    return 0;}


1 0