求先序排列

题目描述

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

输入输出格式

输入格式: 

2行,均为大写字母组成的字符串,表示一棵二叉树的中序与后序排列。 

输出格式: 

1行,表示一棵二叉树的先序。

输入输出样例

输入样例#1:
BADC
BDCA
输出样例#1:
ABCD
思路:
  根据树的后序是根,而中序的前半部分是左树,而后半部分是右树。
  再单独处理左树和右树。
#include<cstdio>
#include<iostream>
#include<queue>
#include<cstring>
#include<cmath>
using namespace std;
char a[100],b[100];
void work(int L,int R)
{
    int i,j,c;
    if(L>R)    return ;
    c=0;
    for(int i=strlen(b+1);i>=1;i--)
    {    
        for(int j=L;j<=R;j++)
        if(a[j]==b[i])
        {
            c=j;
            break;
        }
        if(c)    break;        
    }
    if(c)    printf("%c",a[c]);
    work(L,c-1);work(c+1,R);
}
int main()
{
    cin>>(a+1)>>(b+1);
    work(1,strlen(a+1));
    return 0;
}
 
原文地址:https://www.cnblogs.com/CLGYPYJ/p/7678005.html