SDUTOJ1489求二叉树的先序遍历

版权声明:iQXQZX https://blog.csdn.net/Cherishlife_/article/details/84976640

求二叉树的先序遍历

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 <bits/stdc++.h>
using namespace std;
char s1[100], s2[100], ans[100];
int cnt;
void make(int len, char *s1, char *s2) // 中序、后序 推前序 s1中序s2后序
{
    if (len <= 0)
        return;
    int i = strchr(s1, s2[len - 1]) - s1; // 从s1中搜索s2[len-1] 并返回地址,地址减去首地址即为子树长度
    ans[cnt++] = s2[len - 1];
    make(i, s1, s2);                       // 递归搜索左子树
    make(len - i - 1, s1 + i + 1, s2 + i); //递归搜素右子树 存到地址之后
}
int main()
{
    int n;
    cin >> n;
    while (n--)
    {
        scanf("%s %s", s1, s2);
        cnt = 0;
        int len = strlen(s1);
        make(len, s1, s2);
        ans[len] = '\0'; // 不要忘记封口
        cout << ans << endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Cherishlife_/article/details/84976640