求先序排列

试题 算法训练 求先序排列

问题描述
  给出一棵二叉树的中序与后序排列。求出它的先序排列。(约定树结点用不同的大写字母表示,长度<=8)。

输入格式

  两行,每行一个字符串,分别表示中序和后序排列

输出格式

  一个字符串,表示所求先序排列

  样例输入
  BADC
  BDCA

样例输出

ABCD

 

代码如下:

#include<iostream>
#include<cstring>
using namespace std;

void strcpy1(char *b, char *s1, char *s2, int pos, int len)
{
    int i, t;
    for(i = 0; i < pos; i++)
    {
        s1[i] = b[i];
    }
    s1[i++] = '\0';
    for(t = 0; i < len; i++, t++)
    {
        s2[t] = b[i];
    }
    s2[t] = '\0';

void strcpy2(char *c, char *s2,  char *s3, char *s4, int len)
{
    int i, t = 0;
    int l = strlen(s2);
    for(i = 0; i < len; i++)
    {
        int flag = 1;
        for(int j = 0; j < l; j++)
        {
            if(c[i] == s2[j])
                flag = 0;
        }
        if(flag) s3[t++] = c[i];
        else
        {
            s3[t] = '\0';
            break;
        }
    }
    t = 0;
    for(; i < len - 1; i++)
    {
        s4[t++] = c[i];
    }
    s4[t] = '\0';

void fun(char b[], char c[], int len)
{
    if(len == 0)
    {
        b = c = NULL;
        return ;
    }
    
    char s1[9], s2[9], s3[9], s4[9];
    
    char ch = c[len - 1];
    cout << ch;
    
    int pos = strchr(b, ch) - b;
    
    strcpy1(b, s1, s2, pos, len);
    strcpy2(c, s2, s3, s4, len);
    
    fun(s1, s3, pos);
    fun(s2, s4, len-pos-1);
    
}

int main()
{
    char b[9],  c[9];
    cin >> b >> c;
    int len = strlen(b);
    fun(b, c, len);
    return 0;
}

求先序排列