1. 程式人生 > >給定樹的後序和中序排列求先序排列

給定樹的後序和中序排列求先序排列

問題描述
  給出一棵二叉樹的中序與後序排列。求出它的先序排列。(約定樹結點用不同的大寫字母表示,長度<=8)。輸入格式  兩行,每行一個字串,分別表示中序和後序排列輸出格式  一個字串,表示所求先序排列

  樣例輸入
  BADC
  BDCA樣例輸出       ABCD

演算法思想:我們先去尋找這棵樹的根,即後序排列的最後一個元素,然後在中序排列中找到它,此時在中序排列中,其左邊就是左子樹,右邊就是右子樹,分別記錄下左子樹和右子樹的元素個數,就能同時在後序排列中找到左右子樹的分佈區間,對子樹繼續遞迴重複以上過程即可,程式碼如下。

#include<cstdio>
#include<algorithm>
#include<queue>
#include<iostream>
#include<cstring>
using namespace std;
char mid[10];
char hou[10];
int len;
void Seek(int first,int last,int mfir,int mlast)
{
    if(first>last||mfir>mlast)
    return ;
    char ch=hou[last];
    cout<<ch;
    for(int i=mfir;i<=mlast;i++)
    {
        if(mid[i]==ch)
        {
            Seek(first,first+i-1-mfir,mfir,i-1);
            Seek(last-mlast+i,last-1,i+1,mlast);
            break;
        }
    }
}
int main()
{
    scanf("%s",mid);
    scanf("%s",hou);
    len=strlen(hou);
    Seek(0,len-1,0,len-1);
    return 0;
}