1489求二叉树的先序遍历

求二叉树的先序遍历

Time Limit: 1000 ms Memory Limit: 65536 KiB

Submit Statistic

Problem Description

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

Input

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

Output

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

Sample Input

2
dbgeafc
dgebfca
lnixu
linux

Sample Output

abdegcf
xnliu

Hint

Source

GYX


#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct node
{
    char data;
    struct node *left;
    struct node *right;
};
struct node *creat(int n,char *str1,char *str2)
{
    struct node *root;
    int i;
    if(n==0)
        return NULL;
    root = (struct node *)malloc(sizeof(struct node));
    root->data=str2[n-1];//找到根节点
    printf("%c",root->data);
    for(i=0;i<n;i++)//找到str1中的根节点的位置
    {
        if(str1[i]==str2[n-1])
            break;
    }
    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,len;
    char str1[100],str2[100];
    scanf("%d",&n);
    while(n--)
    {
        memset(str1,0,sizeof(str1));
        memset(str2,0,sizeof(str2));
        scanf("%s",str1);
        scanf("%s",str2);
        len=strlen(str1);
        creat(len,str1,str2);
        printf("\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/rangran/article/details/81632741